package com.platform.qujia.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.qujia.anno.SimpleRepeatedReqLimit;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.constantEnum.integralTypeEnum;
import com.platform.qujia.dao.*;
import com.platform.qujia.enums.*;
import com.platform.qujia.handle.PayOrderHandle;
import com.platform.qujia.param.request.*;
import com.platform.qujia.pay.strategy.YunhuaChannel;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.DivideAccountsSettingDto;
import com.platform.qujia.pojo.dto.ElectronicCardSubRes;
import com.platform.qujia.service.*;
import com.platform.qujia.service.impl.FleetCardServiceImpl;
import com.platform.qujia.service.impl.SxfCallbackServiceImpl;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.exception.EndingException;
import com.platform.qujia.utils.jinkong.JKPayParam;
import com.platform.qujia.utils.jinkong.JKPayUtil;
import com.platform.qujia.utils.sxfpay.SXFPayParam;
import com.platform.qujia.utils.sxfpay.SXFPayUtil;
import com.platform.qujia.utils.tonglianpay.TLPayParam;
import com.platform.qujia.utils.tonglianpay.TLPayUtil;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.TLFusClassPayUtil;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.struct.body.TLFusClassPayParam;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import com.platform.qujia.utils.yunHua.YunHuaParam;
import com.platform.qujia.utils.yunHua.yunHuaPayUtils;
import com.platform.qujia.utils.yunpay.SBPayParam;
import com.platform.qujia.utils.yunpay.SBPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/***
 * <Title> QuJiaPayController </Title>
 * <Description> 趣加 新版小程序订单 App生成订单，与调用第三方支付控制层 </Description>
 * <Date>2021年10月28日</Date>
 */

@RestController
@Api(tags = "趣加App支付")
//@QuJiaRequest()
@CrossOrigin
@Slf4j
public class QuJiaPayV2Controller {

    private static Logger logger = (Logger) LoggerFactory.getLogger(QuJiaPayV2Controller.class);

    @Autowired
    private CouponController couponController;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private ClassSettlementService classSettlementService;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private ReductionActivityService reductionActivityService;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private PosMachineService posMachineService;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private AppUserSuperService appUserSuperService;
    @Resource
    private CouponService couponService;

    @Resource
    private InvoiceService invoiceService;
    @Autowired
    private PayWayMapper payWayMapper;
    @Autowired
    private SuperPayOrderMapper superPayOrderMapper;

    @Resource
    private ReductionActivityBalanceRecordService reductionActivityBalanceRecordService;

    @Autowired
    private CustomerCardSettingDetailService customerCardSettingDetailService;

    @Autowired
    private CustomerCardSettingService customerCardSettingService;
    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;
    @Autowired
    private FleetCardMapper fleetCardMapper;
    @Autowired
    private PhysicalCardBalanceMapper physicalCardBalanceMapper;


    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${qujia.domainName}")
    private String domainName;

    @Value("${qujia.tokenHttp}")
    private String tokenHttp;


    @Value("${qujia.private_pfxPath}")
    private String private_pfxPath;

    @Value("${qujia.public_certPath}")
    private String public_certPath;

    @Value("${qujia.yunhuaPrePayUrl}")
    private String yunHuaPrePayUrl;

    @Value("${qujia.yunhuaPayUrl}")
    private String yunhuaPayUrl;

    @Resource
    private StationEnterpriseCopInfoService stationEnterpriseCopInfoService;

    @Autowired
    private PresentAmountRecordService presentAmountRecordService;
    @Autowired
    private TradePaymentRecordsService tradePaymentRecordsService;
    @Autowired
    private QujiaPayV2Service qujiaPayV2Service;


//    String private_pfxPath="C:\\Users\\zcs\\Desktop\\商户密钥\\私钥.pfx"; //商户私钥地址
//
//    String public_certPath="C:\\Users\\zcs\\Desktop\\商户密钥\\xdzf_cfca_prd.cer"; //现代支付公钥地址


    //    @RequestMapping("/drawCoupons")
//    public String drawCoupons(@RequestBody DrawCoupon drawCoupon){
//        // 调用 ControllerB 的方法
//        String result = couponController.drawCoupons(drawCoupon);
//        return result;
//    }
    /*
     * 小程序创建加油支付订单
     * @param payOrderRequest
     * @return
     */
    @ApiOperation(value = "小程序创建加油支付订单", httpMethod = "POST", notes = "小程序创建加油支付订单")
    @PostMapping(value = "/createOrder", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(@RequestBody PayOrderRequest request) {
        String phone = request.getMobilePhone();
        /*if(StringUtils.isBlank(phone)){
            return ResultData.errorJson("缺少手机号参数");
        }*/
        try {
            logger.info("/createOrder-" + phone + "--request:" + request.toString());
            ReductionActivity reductionActivity = null;
            String userId = request.getUserId();
            if (StringUtils.isNotBlank(userId)) {
                String[] split = userId.split("&");
                request.setUserId(split[0]);
            }

            //记录订单来源
            if (StringUtils.isBlank(request.getUtmSource())) {
                //没有设置9
                if (StringUtils.equals("2", request.getAppType())) {
                    request.setUtmSource("1");
                } else {
                    request.setUtmSource("9");
                }
            }
            if (StringUtils.equals(request.getUtmSource(), "1")) {
                //扫码订单，加油员id不能为空
                if (StringUtils.isBlank(request.getUserId())) {
                    throw new CustomException("加油员id为空");
                }
            }

            //确保参数就位
            if (request.getStationId() == null || StringUtils.isBlank(request.getOrderOriginType()) || StringUtils.isBlank(request.getGunName()) || request.getReceivableAmt() == null) {
                throw new EndingException("缺少必传参数");
            }

            Map<String, Object> resultMap = new HashMap<>();     //返回结果集
            PayOrder newPayOrder = new PayOrder();             //生成订单参数


            Station station = enterpriseService.selectStationById(request.getStationId());
            if (station == null) {
                throw new EndingException("未查询到油站");
            }


            newPayOrder.setEnterpriseId(station.getEnterpriseId());
            newPayOrder.setEnterpriseName(station.getEnterprise().getEnterpriseName());

            //是否启用  必须扫加油员扫码
//            if(StringUtils.isNotBlank(station.getEmployeeAppletFlag()) && "1".equals(station.getEmployeeAppletFlag()) && !StringUtils.isNotBlank(request.getUserId())){
//                throw new EndingException("请扫加油员码进入");
//            }

            newPayOrder.setOrderRandomId(request.getOrderRandomId());
            newPayOrder.setAppType(request.getAppType());
            newPayOrder.setPayType(request.getPayType());
            newPayOrder.setOrderOriginType(request.getOrderOriginType());
            newPayOrder.setStationName(station.getStationName());
            newPayOrder.setUtmSource(request.getUtmSource());

            AppUserInfo appUserInfo = null;

            if (StringUtils.isNotBlank(phone)) {
                AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                queryAppUserInfo.setMobilePhone(phone);
                queryAppUserInfo.setStationId(station.getEnterpriseId());
                appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
            } else if (request.getConsumerId() != null) {
                appUserInfo = appUserInfoService.getById(request.getConsumerId());
            } else if (StringUtils.isNotBlank(request.getOpenId())) {
                AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                queryAppUserInfo.setBlogOpenid(request.getOpenId());
                queryAppUserInfo.setStationId(station.getEnterpriseId());
                appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
            }
//            queryAppUserInfo.setStationId(station.getStationId()); bug修改 20230423

            if (appUserInfo == null) {
                throw new EndingException("查无用户，请重新登录~");
            }

            boolean hasPhone = !MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone());


            resultMap.put("stationName", station.getStationName());
            resultMap.put("stationPic", station.getHeadImg());
            resultMap.put("dialogueAdFlag", station.getDialogueAdFlag());

            newPayOrder.setConsumer(appUserInfo.getBlogNickName());                   //昵称
            newPayOrder.setConsumerId(appUserInfo.getUserId());                       //用户id
            newPayOrder.setCustomerPhone(appUserInfo.getMobilePhone());
            newPayOrder.setOilPersonnelId(request.getUserId());

            String ordNo = generateOrdNo();

            logger.info("/createOrder-" + phone + "--ordNo:" + ordNo);
            newPayOrder.setOrderNo(ordNo);                                          //订单号
            newPayOrder.setStationId(request.getStationId());                  //油站id
            newPayOrder.setStatus("0");                                                //创建订单 未支付状态 0
            newPayOrder.setCreatedDate(new Timestamp(new Date().getTime()));           //创建时间
            newPayOrder.setOilGun(request.getGunName());                        //油枪号
            newPayOrder.setReceivableAmt(Double.valueOf(request.getReceivableAmt()));      //订单应收金额
            newPayOrder.setDzkAmt(Double.valueOf(request.getReceivableAmt()));             //电子卡金额

            //油品价格
            StaOilGun queryOilGun = new StaOilGun();
            queryOilGun.setGunName(request.getGunName());   // 枪号
            queryOilGun.setStationId(request.getStationId());
            StaOilGun staOilGun = enterpriseService.selectStaGunInfo(queryOilGun);
            if (staOilGun == null) {
                throw new EndingException("未查到目标油枪");
            }


            BigDecimal oilPrice = staOilGun.getOilStationPrice();
            BigDecimal oilLiters = new BigDecimal(request.getReceivableAmt()).divide(oilPrice, 4, BigDecimal.ROUND_HALF_UP); //加油升数
            String oilType = staOilGun.getOil().getCardType();

            newPayOrder.setOilPirce(oilPrice.toString()); //油价 原价
            newPayOrder.setOrderType(staOilGun.getOil().getOilClass()); // 油品类
            newPayOrder.setOilName(staOilGun.getOilId().toString()); // 油品id

            newPayOrder.setAmt(Double.valueOf(request.getReceivableAmt())); //实收金额

            newPayOrder.setDiscountAmt(Double.valueOf("0.00")); //优惠金额

            newPayOrder.setOrderLiters(oilLiters.toString()); // 油升数

            resultMap.put("cardFlag", station.getEnterprise().getCardFlag()); //是否开启电子卡

            BigDecimal balance = BigDecimal.ZERO;
            BigDecimal genericBalance = BigDecimal.ZERO;
            boolean notMultiplePay = Objects.equals(0,station.getMultipleOilPayFlag()) || !StringUtils.equals(ElectronCardType.DIESEL.getName(),staOilGun.getOilClass());

            //有手机号且开启电子卡, 才获取电子卡余额，开启多油品支付且订单油品是柴油不查询
            if (hasPhone && "1".equals(station.getEnterprise().getCardFlag()) && notMultiplePay) {
                logger.info("/createOrder-" + phone + "--cardType:" + oilType);
                CustomerCardSetting setting = customerCardSettingService.getOne(CustomerCardSetting.builder().stationId(station.getEnterpriseId()).delFlag("0").build());
                List<CustomerElectronicCard> cardList;
                int genericEnable = 0;
                if (StringUtils.contains(setting.getCardOilsType(), ElectronCardType.GENERIC.getKey())) {
                    cardList = electronicMembershipCardService.queryCustomerElectronicCardList(appUserInfo.getMobilePhone(), new String[]{oilType, ElectronCardType.GENERIC.getKey()}, station);
                    genericEnable = 1;
                    for (CustomerElectronicCard card : cardList) {
                        if (StringUtils.equals(card.getCardOilsType(), ElectronCardType.GENERIC.getKey())) {
                            genericBalance = card.getTotalAmt();
                        } else {
                            balance = card.getTotalAmt();
                        }
                    }
                    if(StringUtils.equals("wx",request.getPayType()) && balance.compareTo(BigDecimal.ZERO) <=0 && genericBalance.compareTo(BigDecimal.ZERO)>0){
                        // 通用卡有余额，且储值卡没有余额，设置true
                        // 只有微信才判断，支付宝没做通用卡
                        request.setGenericPay(Boolean.TRUE);
                    }
                } else {
                    cardList = electronicMembershipCardService.queryCustomerElectronicCardList(appUserInfo.getMobilePhone(), new String[]{oilType}, station);
                    balance = cardList.isEmpty() ? BigDecimal.ZERO : cardList.get(0).getTotalAmt();
                }
                //CustomerElectronicCard customerElectronicCard = electronicMembershipCardService.getCustomerElectronicCard(appUserInfo, oilType, station);
                //balance = customerElectronicCard == null ? BigDecimal.ZERO : customerElectronicCard.getTotalAmt();
                resultMap.put("balance", balance);
                resultMap.put("genericBalance", genericBalance);
                resultMap.put("genericEnable", genericEnable);
            } else {
                resultMap.put("balance", balance);
                resultMap.put("genericBalance", genericBalance);
                resultMap.put("genericEnable", 0);
            }

            // 检验随机码
            if (StringUtils.isNotBlank(request.getOrderRandomId())) {
                checkOrderRandomId(request);
            }
            PayOrderHandle.setPayOrderInvoiceStatus(newPayOrder);
            if (payOrderMapper.insertSelective(newPayOrder) < 1) {
                throw new EndingException("插入订单失败");
            }

            System.out.println("------------");
            BigDecimal reductionAmount = BigDecimal.ZERO;
            String activityRule1 = null;
            String activityRule2 = null;
            List<Object> preferenceMessageList = new ArrayList<>();
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
            if (hasPhone) {
                //计算优惠金额
                log.info("计算优惠金额");
                if (balance.compareTo(BigDecimal.ZERO) > 0 || genericBalance.compareTo(BigDecimal.ZERO) > 0) {
                    // 创建订单时，前端默认选择电子卡支付，电子卡有余额pay_type手动改成电子卡，否则不会参与仅限电子卡的立减优惠
                    request.setPayType("dzk");
                    // 电子卡标识也设置一下，计算渠道费用到
                    request.setCardFlag("2");
                }
                // 计算消费立减
                Map<String, Object> amountMap = reductionActivityService.selectReductionByPayOrder(appUserInfo, newPayOrder, "CSP", request, station,staOilGun);
                if (amountMap.get("activityRule") != null) {
                    activityRule1 = (String) amountMap.get("activityRule");
                }
                // 计算充值立减
                //BigDecimal rCHReductionAmt=reductionActivityService.getRCHReductionAmt(appUserInfo,newPayOrder,request,station);
                Map<String, Object> rCHResult = reductionActivityService.getRCHReductionAmt(appUserInfo, newPayOrder, request, station);
                if(rCHResult.containsKey("reductionActivity")){
                    reductionActivity= (ReductionActivity) rCHResult.get("reductionActivity");
                }

                //记录 充值立减活动优惠金额、消费立减活动优惠金额
                if (amountMap.get("reductionAmount") != null) {
                    newPayOrder.setConsumeDiscountAmt(new BigDecimal(amountMap.get("reductionAmount").toString()));
                }
                if (rCHResult.get("rCHReductionAmt") != null) {
                    newPayOrder.setRechargeDiscountAmt((BigDecimal) rCHResult.get("rCHReductionAmt"));
                }
                if(Objects.nonNull(enterprise) && Objects.nonNull(enterprise.getIsShow())
                        && enterprise.getIsShow().equals(1)){
                    ReductionRules consumeRules =(ReductionRules) amountMap.get("rule");
                    ReductionRules rechargeRules =(ReductionRules) rCHResult.get("rule");
                    // 过滤 每升立减优惠
                    List<String> type = Arrays.asList("AAL","AALL");
                    if (Objects.nonNull(consumeRules) && StringUtils.isNotEmpty(consumeRules.getActivityType())
                            && type.contains(consumeRules.getActivityType())) {
                        preferenceMessageList.add(consumeRules);
                    }
                    if (Objects.nonNull(rechargeRules) && StringUtils.isNotEmpty(rechargeRules.getActivityType())
                            && type.contains(rechargeRules.getActivityType())) {
                        preferenceMessageList.add(rechargeRules);
                    }
                }


                if (amountMap.get("activityRule") != null) {
                    activityRule2 = (String) rCHResult.get("activityRule");
                }
                BigDecimal rCHReductionAmt = (BigDecimal) rCHResult.get("rCHReductionAmt");
                List<CouponUser> couponList2 = (List<CouponUser>) rCHResult.get("couponList");

                reductionAmount = reductionAmount.add(rCHReductionAmt);

                if (amountMap != null && amountMap.containsKey("reductionAmount") && amountMap.get("reductionAmount") != null) {

                    reductionAmount = reductionAmount.add(new BigDecimal(amountMap.get("reductionAmount").toString()));
                    // 每笔订单最低付款额度0.01
                    if ((new BigDecimal(request.getReceivableAmt()).subtract(reductionAmount)).compareTo(new BigDecimal("0.01")) <= 0) {
                        reductionAmount = new BigDecimal(request.getReceivableAmt()).subtract(new BigDecimal("0.01"));
                    }
                }


                //可用的优惠券列表
                if (amountMap != null && amountMap.containsKey("couponList") && amountMap.get("couponList") != null) {
                    List<CouponUser> couponList = (List<CouponUser>) amountMap.get("couponList");
                    Set<CouponUser> quchong = new HashSet<>();
                    quchong.addAll(couponList);
                    quchong.addAll(couponList2);
                    List<CouponUser> total = new ArrayList<>(quchong);
                    resultMap.put("couponList", total);
                }

                resultMap.put("couponEnabledFlag", station.getEnterprise().getCouponEnabledFlag());

                //油企是否开启优惠券功能

                if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                    Map<String, Object> p = new HashMap<>();
                    p.put("issueType", "3");
                    p.put("stationId", station.getStationId());
                    p.put("curTime", new Date());
                    //获取油企给当前油站设置的issueType=3时，消费完成后的可选择领取的优惠券活动;
                    List<CouponIssue> couponIssueInfo = couponService.selectCouponListByCouponIssueId(p);
                    if (null != couponIssueInfo && couponIssueInfo.size() >= 1) {
                        resultMap.put("couponIssueInfo", couponIssueInfo.get(0).getCouponIssueId());
                    }

                }
            } else {
                // 闪付计算立减
                // 以游客身份访问，开启优惠卷标识设为0
                resultMap.put("couponEnabledFlag", "0");
                reductionAmount = reductionActivityService.selectVisitorReductionByPayOrder(new BigDecimal(request.getReceivableAmt()), newPayOrder, appUserInfo);
                // 过滤 每升立减优惠
                List<String> type = Arrays.asList("AAL","AALL");
                if(Objects.nonNull(enterprise) && Objects.nonNull(enterprise.getIsShow())
                        && enterprise.getIsShow().equals(1) && Objects.nonNull(appUserInfo.getFRules())){
                    ReductionRules fRules = appUserInfo.getFRules();
                    if (StringUtils.isNotEmpty(fRules.getActivityType()) && type.contains(fRules.getActivityType())) {
                        preferenceMessageList.add(fRules);
                    }
                }
            }
            resultMap.put("isShow",enterprise.getIsShow());
            resultMap.put("preferenceMessageList",preferenceMessageList);

            newPayOrder.setDiscountAmt(reductionAmount.doubleValue());
            //实收金额
            BigDecimal amt = new BigDecimal(request.getReceivableAmt()).subtract(reductionAmount);

            CouponUser couponUser = null;
            if (hasPhone && null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                //选择活动力度最大的优惠券 开启多油品支付且订单油品是柴油不选择
                if (notMultiplePay) {
                    couponUser = reductionActivityService.getDiscountMaxCoupon(amt, (List<CouponUser>) resultMap.get("couponList"),appUserInfo.getMobilePhone());
                }
                if(reductionActivity!=null){
                    if(StringUtils.isNotEmpty(reductionActivity.getActivityRule())&&reductionActivity.getActivityRule().equals("2")){
                        couponUser=null;
                    }
                }
                if (request.getPayType().equals("zfb")) {
                    //排除支付宝
                    couponUser = null;
                }
                if (activityRule1 == null && activityRule2 == null) {
                    //可以选优惠力度最大的优惠券
                } else if (activityRule1 == null && activityRule2 != null) {
                    if (activityRule2.equals("2")) {
                        couponUser = null;
                    }
                } else if (activityRule1 != null && activityRule2 == null) {
                    if (activityRule1.equals("2")) {
                        couponUser = null;
                    }
                } else {
                    if (activityRule1.equals("2") || activityRule2.equals("2")) {
                        couponUser = null;
                    }
                }
                if (couponUser != null && couponUser.getFinalCouponAmount() != null) {
                    BigDecimal finalCouponAmount = couponUser.getFinalCouponAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
                    newPayOrder.setDiscountCouponAmt(finalCouponAmount.doubleValue());
                    newPayOrder.setCouponUserId(couponUser.getCouponUserId().toString());
                    newPayOrder.setDiscountCoupon(couponUser.getCouponUserId().toString());
                    amt = amt.subtract(finalCouponAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (amt.compareTo(BigDecimal.ZERO) < 1) {
                        amt = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    resultMap.put("discountCouponAmt", finalCouponAmount);
                    resultMap.put("discountCoupon", couponUser.getCouponUserId());
                    resultMap.put("discountMaxCoupon", couponUser);
                }
            }
            newPayOrder.setAmt(amt.doubleValue());
            newPayOrder.setDzkAmt(amt.doubleValue());
//            Map<String, Object> map=null;
//            if (request.getPayType().equals("wx")) {
//                 map = payOrderMapper.selectServiceCharge(request.getStationId(),1);
//            }else if (request.getPayType().equals("zfb")){
//                 map = payOrderMapper.selectServiceCharge(request.getStationId(),2);
//            }

            // 不加渠道费的实付金额
            BigDecimal oriAmt = amt;
            // 计算渠道费
            calculateChannelFee(amt, newPayOrder, request, resultMap);

            resultMap.put("finalAmount", request.getReceivableAmt());

            payOrderMapper.updateByPrimaryKeySelective(newPayOrder);
            amt = BigDecimal.valueOf(newPayOrder.getAmt());
            //优惠价格
            BigDecimal discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
            resultMap.put("discountPrice", oilPrice.setScale(2, BigDecimal.ROUND_HALF_UP));                      //优惠价格
            resultMap.put("discountAmt", reductionAmount.setScale(2, BigDecimal.ROUND_HALF_UP));                      //优惠金额       减这个数
            resultMap.put("isShowPaymentCommission",station.getIsShowPaymentCommission());
            if (station.getIsShowPaymentAmtCommission()==0) {
                resultMap.put("amt",oriAmt.setScale(2,RoundingMode.HALF_UP));
            }else{
                resultMap.put("amt", amt.setScale(2, BigDecimal.ROUND_HALF_UP));                                          //实收金额
            }
            resultMap.put("dzkAmt", amt.setScale(2, BigDecimal.ROUND_HALF_UP));                                       //电子卡支付金额
            resultMap.put("receivableAmt", request.getReceivableAmt()); //应收金额
            resultMap.put("oilLiters", oilLiters);                              //加油升数
            resultMap.put("ordNo", ordNo);                                      //订单号
            resultMap.put("cardType", oilType);    //该油品对应的电子卡类型

//            logger.info("/createOrder-"+ phone +"--返回前端的结果:" + resultMap.toString());
            logger.info("/createOrder-" + phone + "--返回前端的结果:" + ResultData.successJson(resultMap).toString());
            return ResultData.successJson(resultMap);

        } catch (EndingException e) {
            logger.error("/createOrder-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/createOrder-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }
    }

    @ApiOperation(value = "自动切换支付渠道", httpMethod = "POST", notes = "自动切换支付渠道")
    @PostMapping(value = "/changeAutoPayWay", produces = "application/json;charset=UTF-8")
    public int changeAutoPayWay(@RequestBody AutoPayWay autoPayWay) {
        classSettlementService.changeAutoPayWayBGApi(autoPayWay);
return 1;
    }

    @ApiOperation(value = "创建订单不包含任何优惠活动", httpMethod = "POST", notes = "创建订单不包含任何优惠活动")
    @PostMapping(value = "/createOrderNotContainActivity", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public String createOrderNotContainActivity(@RequestBody PayOrderRequest request) {
        try {
            logger.info("/createOrderNotContainActivity-" + "--request:" + request.toString());
            String ordNo = generateOrdNo();
            logger.info("/createOrderNotContainActivity-" + "--ordNo:" + ordNo);
            PayOrder newPayOrder = new PayOrder();             //生成订单参数
            Gson gson = new Gson();
            newPayOrder = gson.fromJson(gson.toJson(request), PayOrder.class);
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(request.getEnterpriseId());
            if (enterprise == null) {
                throw new EndingException("未查询到油企");
            }
            if (request.getStationId() == null) {
                throw new EndingException("缺少油站id");
            }
            Station station = enterpriseService.selectStationById(request.getStationId());
            newPayOrder.setEnterpriseId(enterprise.getEnterpriseId());
            newPayOrder.setEnterpriseName(enterprise.getEnterpriseName());
            if (StringUtils.isNotEmpty(request.getReceivableAmt())) {
                newPayOrder.setAmt(new Double(request.getReceivableAmt()));
            } else {
                newPayOrder.setAmt(0d);
            }
            newPayOrder.setDiscountAmt(0d);
            newPayOrder.setDiscountCouponAmt(0d);
            newPayOrder.setDzkAmt(0d);
            newPayOrder.setServiceCharge(BigDecimal.ZERO);
            newPayOrder.setIsPrint(0);
            newPayOrder.setActualRechargeAmt(BigDecimal.ZERO);
            newPayOrder.setRechargeDiscountAmt(BigDecimal.ZERO);
            newPayOrder.setConsumeDiscountAmt(BigDecimal.ZERO);
            newPayOrder.setStatus("0");
            newPayOrder.setOrderNo(ordNo);
            newPayOrder.setCreatedDate(new Date());
            newPayOrder.setStationId(request.getStationId());
            newPayOrder.setStationName(station.getStationName());
            newPayOrder.setUtmSource("1");//扫码订单
            PayOrderHandle.setPayOrderInvoiceStatus(newPayOrder);
            if (payOrderMapper.insertSelective(newPayOrder) < 1) {
                throw new EndingException("插入订单失败");
            }
            return ResultData.successJson(newPayOrder);

        } catch (Exception e) {
            logger.error("/createOrderNotContainActivity-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }


    }

    /*
     * 小程序创建加油支付订单
     * @param payOrderRequest
     * @return
     */
    @ApiOperation(value = "根据电子卡计算优惠", httpMethod = "POST", notes = "根据电子卡计算优惠")
    @PostMapping(value = "/updateOrderByDzk", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public String updateOrderByDzk(@RequestBody PayOrderRequest request) {
        String phone = request.getMobilePhone();
        /*if(StringUtils.isBlank(phone)){
            return ResultData.errorJson("缺少手机号参数");
        }*/
        try {
            logger.info("/createOrder-" + phone + "--request:" + request.toString());

            //确保参数就位
            if (request.getStationId() == null || StringUtils.isBlank(request.getOrderOriginType()) || StringUtils.isBlank(request.getGunName()) || request.getReceivableAmt() == null) {
                throw new EndingException("缺少必传参数");
            }

            Map<String, Object> resultMap = new HashMap<>();     //返回结果集
            PayOrder newPayOrder = new PayOrder();             //生成订单参数


            Station station = enterpriseService.selectStationById(request.getStationId());
            if (station == null) {
                throw new EndingException("未查询到油站");
            }


            newPayOrder.setEnterpriseId(station.getEnterpriseId());
            newPayOrder.setEnterpriseName(station.getEnterprise().getEnterpriseName());

            //是否启用  必须扫加油员扫码
            if (StringUtils.isNotBlank(station.getEmployeeAppletFlag()) && "1".equals(station.getEmployeeAppletFlag()) && !StringUtils.isNotBlank(request.getUserId())) {
                throw new EndingException("请扫加油员码进入");
            }

            newPayOrder.setOrderRandomId(request.getOrderRandomId());
            newPayOrder.setAppType(request.getAppType());
            newPayOrder.setPayType(request.getPayType());
            newPayOrder.setOrderOriginType(request.getOrderOriginType());
            newPayOrder.setStationName(station.getStationName());

            AppUserInfo appUserInfo = null;

            if (StringUtils.isNotBlank(phone)) {
                AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                queryAppUserInfo.setMobilePhone(phone);
                queryAppUserInfo.setStationId(station.getEnterpriseId());
                appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
            } else if (request.getConsumerId() != null) {
                appUserInfo = appUserInfoService.getById(request.getConsumerId());
            } else if (StringUtils.isNotBlank(request.getOpenId())) {
                AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                queryAppUserInfo.setBlogOpenid(request.getOpenId());
                queryAppUserInfo.setStationId(station.getEnterpriseId());
                appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
            }

            if (appUserInfo == null) {
                throw new EndingException("查无用户，请重新登录~");
            }
            boolean hasPhone = !MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone());
            resultMap.put("stationName", station.getStationName());
            resultMap.put("stationPic", station.getHeadImg());
            resultMap.put("dialogueAdFlag", station.getDialogueAdFlag());

            newPayOrder.setConsumer(appUserInfo.getBlogNickName());                   //昵称
            newPayOrder.setConsumerId(appUserInfo.getUserId());                       //用户id
            newPayOrder.setCustomerPhone(appUserInfo.getMobilePhone());
            newPayOrder.setOilPersonnelId(request.getUserId());

            String ordNo = generateOrdNo();

            logger.info("/createOrder-" + phone + "--ordNo:" + ordNo);
            newPayOrder.setOrderNo(ordNo);                                          //订单号
            newPayOrder.setStationId(request.getStationId());                  //油站id
            newPayOrder.setStatus("0");                                                //创建订单 未支付状态 0
            newPayOrder.setCreatedDate(new Timestamp(new Date().getTime()));           //创建时间
            newPayOrder.setOilGun(request.getGunName());                        //油枪号
            newPayOrder.setReceivableAmt(Double.valueOf(request.getReceivableAmt()));      //订单应收金额
            newPayOrder.setDzkAmt(Double.valueOf(request.getReceivableAmt()));             //电子卡金额

            //油品价格
            StaOilGun queryOilGun = new StaOilGun();
            queryOilGun.setGunName(request.getGunName());   // 枪号
            queryOilGun.setStationId(request.getStationId());
            StaOilGun staOilGun = enterpriseService.selectStaGunInfo(queryOilGun);
            if (staOilGun == null) {
                throw new EndingException("未查到目标油枪");
            }


            BigDecimal oilPrice = staOilGun.getOilStationPrice();
            BigDecimal oilLiters = new BigDecimal(request.getReceivableAmt()).divide(oilPrice, 4, BigDecimal.ROUND_HALF_UP); //加油升数
            String oilType = staOilGun.getOil().getCardType();

            newPayOrder.setOilPirce(oilPrice.toString()); //油价 原价
            newPayOrder.setOrderType(staOilGun.getOil().getOilClass()); // 油品类
            newPayOrder.setOilName(staOilGun.getOilId().toString()); // 油品id

            newPayOrder.setAmt(Double.valueOf(request.getReceivableAmt())); //实收金额

            newPayOrder.setDiscountAmt(Double.valueOf("0.00")); //优惠金额

            newPayOrder.setOrderLiters(oilLiters.toString()); // 油升数

            resultMap.put("cardFlag", station.getEnterprise().getCardFlag()); //是否开启电子卡
            BigDecimal balance = BigDecimal.ZERO;
            BigDecimal genericBalance = BigDecimal.ZERO;

            //获取电子卡余额
            if (hasPhone && "1".equals(station.getEnterprise().getCardFlag())) {
                logger.info("/createOrder-" + phone + "--cardType:" + oilType);
                CustomerCardSetting setting = customerCardSettingService.getOne(CustomerCardSetting.builder().stationId(station.getEnterpriseId()).delFlag("0").build());
                List<CustomerElectronicCard> cardList;
                int genericEnable = 0;
                if (StringUtils.contains(setting.getCardOilsType(), ElectronCardType.GENERIC.getKey())) {
                    cardList = electronicMembershipCardService.queryCustomerElectronicCardList(appUserInfo.getMobilePhone(), new String[]{oilType, ElectronCardType.GENERIC.getKey()}, station);
                    genericEnable = 1;
                    for (CustomerElectronicCard card : cardList) {
                        if (StringUtils.equals(card.getCardOilsType(), ElectronCardType.GENERIC.getKey())) {
                            genericBalance = card.getTotalAmt();
                        } else {
                            balance = card.getTotalAmt();
                        }
                    }
                } else {
                    cardList = electronicMembershipCardService.queryCustomerElectronicCardList(appUserInfo.getMobilePhone(), new String[]{oilType}, station);
                    balance = cardList.isEmpty() ? BigDecimal.ZERO : cardList.get(0).getTotalAmt();
                }
                //CustomerElectronicCard customerElectronicCard = electronicMembershipCardService.getCustomerElectronicCard(appUserInfo, oilType, station);
                //balance = customerElectronicCard == null ? BigDecimal.ZERO : customerElectronicCard.getTotalAmt();
                resultMap.put("balance", balance);
                resultMap.put("genericBalance", genericBalance);
                resultMap.put("genericEnable", genericEnable);
            } else {
                resultMap.put("balance", balance);
                resultMap.put("genericBalance", genericBalance);
                resultMap.put("genericEnable", 0);
            }

            // 检验随机码
            if (StringUtils.isNotBlank(request.getOrderRandomId())) {
                checkOrderRandomId(request);
            }

//            if(payOrderMapper.insertSelective(newPayOrder) < 1) {
//                throw new EndingException("插入订单失败");
//            }
            BigDecimal reductionAmount = BigDecimal.ZERO;
            if (hasPhone) {
                //计算优惠金额
                if (StringUtils.equals("2", request.getCardFlag())) {
                    // 更新订单时，选择了电子卡支付，pay_type手动改成电子卡，否则不会参与仅限电子卡的立减优惠
                    request.setPayType("dzk");
                }
                Map<String, Object> amountMap = reductionActivityService.selectReductionByPayOrder(appUserInfo, newPayOrder, "CSP", request, station,staOilGun);


                if (amountMap != null && amountMap.containsKey("reductionAmount") && amountMap.get("reductionAmount") != null) {

                    reductionAmount = new BigDecimal(amountMap.get("reductionAmount").toString());
                    // 每笔订单最低付款额度0.01
                    if ((new BigDecimal(request.getReceivableAmt()).subtract(reductionAmount)).compareTo(new BigDecimal("0.01")) <= 0) {
                        reductionAmount = new BigDecimal(request.getReceivableAmt()).subtract(new BigDecimal("0.01"));
                    }
                }


                //可用的优惠券列表
                if (amountMap != null && amountMap.containsKey("couponList") && amountMap.get("couponList") != null) {
                    List<CouponUser> couponList = (List<CouponUser>) amountMap.get("couponList");
                    resultMap.put("couponList", couponList);
                }

                resultMap.put("couponEnabledFlag", station.getEnterprise().getCouponEnabledFlag());

                //油企是否开启优惠券功能
                if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                    Map<String, Object> p = new HashMap<>();
                    p.put("issueType", "3");
                    p.put("stationId", station.getStationId());
                    p.put("curTime", new Date());
                    //获取油企给当前油站设置的issueType=3时，消费完成后的可选择领取的优惠券活动;
                    List<CouponIssue> couponIssueInfo = couponService.selectCouponListByCouponIssueId(p);
                    if (null != couponIssueInfo && couponIssueInfo.size() >= 1) {
                        resultMap.put("couponIssueInfo", couponIssueInfo.get(0).getCouponIssueId());
                    }
                }
            } else {
                // 以游客身份访问，开启优惠卷标识设为0
                resultMap.put("couponEnabledFlag", "0");
                reductionAmount = reductionActivityService.selectVisitorReductionByPayOrder(new BigDecimal(request.getReceivableAmt()), newPayOrder, appUserInfo);
            }


            newPayOrder.setDiscountAmt(reductionAmount.doubleValue());
            //实收金额
            BigDecimal amt = new BigDecimal(request.getReceivableAmt()).subtract(reductionAmount);
            newPayOrder.setAmt(amt.doubleValue());
            newPayOrder.setDzkAmt(amt.doubleValue());

            // 不加渠道费的实付金额
            BigDecimal oriAmt = amt;
            // 计算渠道费
            calculateChannelFee(amt, newPayOrder, request, resultMap);

            payOrderMapper.updateByPrimaryKeySelective(newPayOrder);
            amt = BigDecimal.valueOf(newPayOrder.getAmt());
            //优惠价格
            BigDecimal discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
            resultMap.put("discountPrice", discountPrice);                      //优惠价格
            resultMap.put("discountAmt", reductionAmount);                      //优惠金额
            resultMap.put("isShowPaymentCommission",station.getIsShowPaymentCommission());
            if (station.getIsShowPaymentAmtCommission()==0) {
                resultMap.put("amt",oriAmt.setScale(2,RoundingMode.HALF_UP));
            }else{
                resultMap.put("amt", amt.setScale(2, BigDecimal.ROUND_HALF_UP));                                          //实收金额
            }
            resultMap.put("dzkAmt", amt);                                       //电子卡支付金额
            resultMap.put("receivableAmt", request.getReceivableAmt()); //应收金额
            resultMap.put("oilLiters", oilLiters);                              //加油升数
            resultMap.put("ordNo", ordNo);                                      //订单号
            resultMap.put("cardType", oilType);    //该油品对应的电子卡类型

            logger.info("/createOrder-" + phone + "--返回前端的结果:" + resultMap.toString());

            return ResultData.successJson(resultMap);

        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/createOrder-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }
    }


    /*
     * 小程序创建加油支付订单
     * @param payOrderRequest
     * @return
     */
    @ApiOperation(value = "有优惠卷创建订单", httpMethod = "POST", notes = "有优惠卷创建订单")
    @PostMapping(value = "/updateOrderByCoupon", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public String updateOrderByCoupon(@RequestBody PayOrderRequest request) {

        try {
            logger.info("/updateOrderByCoupon-" + request.getOrderNo() + "--request:" + request.toString());
            //确保参数就位
            if (request.getOrderNo() == null || "".equals(request.getOrderNo())) {
                throw new Exception("订单号未上传");
            }
            Map<String, Object> a= payOrderService.cherkCouponCount(request);
            if(a.get("status").equals("2")){
                String msg = a.get("msg").toString();
                throw new Exception(msg);
            }

            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(request.getOrderNo());
            if (payOrder == null) {
                throw new Exception("当前订单号不存在订单");
            }
            if (payOrder.getStatus().equals("1")) {
                logger.info("当前订单已被支付");
                throw new Exception("当前订单已被支付");
            }

            AppUserInfo appUserInfo = null;
            String phone = payOrder.getCustomerPhone();
            if (StringUtils.isNotBlank(phone)) {
                AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                queryAppUserInfo.setMobilePhone(phone);
                queryAppUserInfo.setStationId(payOrder.getEnterpriseId());
                appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
            } else if (request.getConsumerId() != null) {
                appUserInfo = appUserInfoService.getById(request.getConsumerId());
            } else if (StringUtils.isNotBlank(request.getOpenId())) {
                AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                queryAppUserInfo.setBlogOpenid(request.getOpenId());
                queryAppUserInfo.setStationId(payOrder.getEnterpriseId());
                appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
            }
            if (appUserInfo == null) {
                throw new EndingException("查无用户，请重新登录~");
            }

            boolean hasPhone = !MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone());
            Map<String, Object> resultMap = new HashMap<>();     //返回结果集
            resultMap.put("stationName", payOrder.getStationName());

            Station station = enterpriseService.selectStationById(request.getStationId());

            resultMap.put("stationPic", station.getHeadImg());
            resultMap.put("dialogueAdFlag", station.getDialogueAdFlag());
            resultMap.put("cardFlag", station.getEnterprise().getCardFlag()); //是否开启电子卡
            //油品价格
            StaOilGun queryOilGun = new StaOilGun();
            queryOilGun.setGunName(payOrder.getOilGun());   // 枪号
            queryOilGun.setStationId(payOrder.getStationId());
            StaOilGun staOilGun = enterpriseService.selectStaGunInfo(queryOilGun);
            BigDecimal balance = BigDecimal.ZERO;
            BigDecimal genericBalance = BigDecimal.ZERO;

            //获取电子卡余额
            if (hasPhone && "1".equals(station.getEnterprise().getCardFlag())) {
                String oilType = staOilGun.getOil().getCardType();
                CustomerCardSetting setting = customerCardSettingService.getOne(CustomerCardSetting.builder().stationId(station.getEnterpriseId()).delFlag("0").build());
                List<CustomerElectronicCard> cardList;
                int genericEnable = 0;
                if (StringUtils.contains(setting.getCardOilsType(), ElectronCardType.GENERIC.getKey())) {
                    cardList = electronicMembershipCardService.queryCustomerElectronicCardList(appUserInfo.getMobilePhone(), new String[]{oilType, ElectronCardType.GENERIC.getKey()}, station);
                    genericEnable = 1;
                    for (CustomerElectronicCard card : cardList) {
                        if (StringUtils.equals(card.getCardOilsType(), ElectronCardType.GENERIC.getKey())) {
                            genericBalance = card.getTotalAmt();
                        } else {
                            balance = card.getTotalAmt();
                        }
                    }
                } else {
                    cardList = electronicMembershipCardService.queryCustomerElectronicCardList(appUserInfo.getMobilePhone(), new String[]{oilType}, station);
                    balance = cardList.isEmpty() ? BigDecimal.ZERO : cardList.get(0).getTotalAmt();
                }
                //CustomerElectronicCard customerElectronicCard = electronicMembershipCardService.getCustomerElectronicCard(appUserInfo, oilType, station);
                //balance = customerElectronicCard == null ? BigDecimal.ZERO : customerElectronicCard.getTotalAmt();
                resultMap.put("balance", balance);
                resultMap.put("genericBalance", genericBalance);
                resultMap.put("genericEnable", genericEnable);
            } else {
                resultMap.put("balance", balance);
                resultMap.put("genericBalance", genericBalance);
                resultMap.put("genericEnable", 0);
            }
            BigDecimal reductionAmount = BigDecimal.ZERO;
            BigDecimal couponAmount = BigDecimal.ZERO;
            List<Object> preferenceMessageList = new ArrayList<>();
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
            if (hasPhone) {
                payOrder.setCouponUserId(request.getCouponUserId());
                payOrder.setDiscountCoupon(request.getCouponUserId());
                if (StringUtils.equals("2", request.getCardFlag())) {
                    // 更新订单时，电子卡有余额，且选择了电子卡支付，pay_type手动改成电子卡，否则不会参与仅限电子卡的立减优惠
                    request.setPayType("dzk");
                }
                //计算优惠金额 消费
                Map<String, Object> amountMap = reductionActivityService.selectReductionByPayOrderCoupon(appUserInfo, payOrder, "CSP", request, station, staOilGun);
                //BigDecimal rCHReductionAmt=reductionActivityService.getRCHReductionAmt(appUserInfo,payOrder,request,station);
                //String oilName = payOrder.getOilName();
                payOrder.setOilName(staOilGun.getOilId().toString());
                // 充值
                Map<String, Object> rCHResult = reductionActivityService.getRCHReductionAmt(appUserInfo, payOrder, request, station);

                //记录 充值立减活动优惠金额、消费立减活动优惠金额
                if (amountMap.get("reductionAmount") != null) {
                    payOrder.setConsumeDiscountAmt(new BigDecimal(amountMap.get("reductionAmount").toString()));
                }
                if (rCHResult.get("rCHReductionAmt") != null) {
                    payOrder.setRechargeDiscountAmt((BigDecimal) rCHResult.get("rCHReductionAmt"));
                }

                if(Objects.nonNull(enterprise) && Objects.nonNull(enterprise.getIsShow())
                        && enterprise.getIsShow().equals(1)){
                    ReductionRules consumeRules =(ReductionRules) amountMap.get("rule");
                    ReductionRules rechargeRules =(ReductionRules) rCHResult.get("rule");
                    log.info("consumeRules : [{}]",JSONObject.toJSONString(consumeRules));
                    log.info("rechargeRules : [{}]",JSONObject.toJSONString(rechargeRules));
                    // 过滤 每升立减优惠
                    List<String> type = Arrays.asList("AAL","AALL");
                    if (Objects.nonNull(consumeRules) && StringUtils.isNotEmpty(consumeRules.getActivityType())
                            && type.contains(consumeRules.getActivityType())) {
                        preferenceMessageList.add(consumeRules);
                    }
                    if (Objects.nonNull(rechargeRules) && StringUtils.isNotEmpty(rechargeRules.getActivityType())
                            && type.contains(rechargeRules.getActivityType())) {
                        preferenceMessageList.add(rechargeRules);
                    }
                }
                //payOrder.setOilName(oilName);
                BigDecimal rCHReductionAmt = (BigDecimal) rCHResult.get("rCHReductionAmt");
                List<CouponUser> couponList2 = (List<CouponUser>) rCHResult.get("couponList");
                //log.info("立减金额："+rCHReductionAmt);
                Integer labelId = null;
                String labelName = null;

                reductionAmount = reductionAmount.add(rCHReductionAmt);

                if (amountMap != null && amountMap.containsKey("reductionAmount") && amountMap.get("reductionAmount") != null) {
                    reductionAmount = reductionAmount.add(new BigDecimal(amountMap.get("reductionAmount").toString()));
                    // 每笔订单最低付款额度0.01
                    if ((new BigDecimal(payOrder.getReceivableAmt()).subtract(reductionAmount)).compareTo(new BigDecimal("0.01")) <= 0) {
                        reductionAmount = new BigDecimal(payOrder.getReceivableAmt()).subtract(new BigDecimal("0.01"));
                    }
                }
                if (amountMap != null && amountMap.containsKey("activityId") && amountMap.get("activityId") != null) {
                    payOrder.setActivityId(Long.valueOf(amountMap.get("activityId").toString()));
                }
                if (amountMap != null && amountMap.containsKey("couponAmount") && amountMap.get("couponAmount") != null) {
                    couponAmount = new BigDecimal(amountMap.get("couponAmount").toString());
                    payOrder.setDiscountCouponAmt(couponAmount.doubleValue());
                }
                //  拉取标签信息，将标签信息添加到对应的订单之中
                if (amountMap != null && amountMap.containsKey("labelId") && amountMap.get("labelId") != null) {
                    labelId = new Integer(amountMap.get("labelId").toString());
                    payOrder.setLabelId(labelId);
                }
                if (amountMap != null && amountMap.containsKey("labelName") && amountMap.get("labelName") != null) {
                    labelName = amountMap.get("labelName").toString();
                    payOrder.setLabelName(labelName);
                }

                //可用的优惠券列表
                if (amountMap != null && amountMap.containsKey("couponList") && amountMap.get("couponList") != null) {
                    List<CouponUser> couponList = (List<CouponUser>) amountMap.get("couponList");
                    Set<CouponUser> quchong = new HashSet<>();
                    quchong.addAll(couponList);
                    quchong.addAll(couponList2);
                    List<CouponUser> total = new ArrayList<>(quchong);
                    resultMap.put("couponList", total);
                }

                resultMap.put("couponEnabledFlag", station.getEnterprise().getCouponEnabledFlag());

                //油企是否开启优惠券功能
                if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                    Map<String, Object> p = new HashMap<>();
                    p.put("issueType", "3");
                    p.put("stationId", station.getStationId());
                    p.put("curTime", new Date());
                    //获取油企给当前油站设置的issueType=3时，消费完成后的可选择领取的优惠券活动;
                    List<CouponIssue> couponIssueInfo = couponService.selectCouponListByCouponIssueId(p);
                    if (null != couponIssueInfo && couponIssueInfo.size() >= 1) {
                        resultMap.put("couponIssueInfo", couponIssueInfo.get(0).getCouponIssueId());
                    }
                }

            } else {
                // 以游客身份访问，开启优惠卷标识设为0
                resultMap.put("couponEnabledFlag", "0");
                String oilName = payOrder.getOilName();
                payOrder.setOilName(String.valueOf(payOrder.getOilId()));
                reductionAmount = reductionActivityService.selectVisitorReductionByPayOrder(BigDecimal.valueOf(payOrder.getReceivableAmt()), payOrder, appUserInfo);
                payOrder.setOilName(oilName);
                // 闪付
                // 过滤 每升立减优惠
                List<String> type = Arrays.asList("AAL","AALL");
                if(Objects.nonNull(enterprise) && Objects.nonNull(enterprise.getIsShow())
                        && enterprise.getIsShow().equals(1) && Objects.nonNull(appUserInfo.getFRules())){
                    ReductionRules fRules = appUserInfo.getFRules();
                    if (StringUtils.isNotEmpty(fRules.getActivityType()) && type.contains(fRules.getActivityType())) {
                        preferenceMessageList.add(fRules);
                    }
                }
            }
            resultMap.put("isShow",enterprise.getIsShow());
            resultMap.put("preferenceMessageList",preferenceMessageList);

            BigDecimal amt = new BigDecimal(payOrder.getReceivableAmt()).subtract(reductionAmount);
            BigDecimal CouponAmt = new BigDecimal(payOrder.getReceivableAmt()).subtract(reductionAmount).subtract(couponAmount);
            CouponUser couponUser = null;
            resultMap.put("discountCouponAmt", couponAmount.setScale(2, BigDecimal.ROUND_HALF_UP));                         //优惠券优惠金额
            if (hasPhone && null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                if (request.getCouponUserId() == null) {
                    //选择优惠力度最大的优惠券
                    //couponUser = reductionActivityService.getDiscountMaxCoupon(amt, (List<CouponUser>) resultMap.get("couponList"));
                    if (request.getPayType().equals("zfb")) {
                        //排除支付宝
                        couponUser = null;
                    }
                    if (couponUser != null && couponUser.getFinalCouponAmount() != null) {
                        BigDecimal finalCouponAmount = couponUser.getFinalCouponAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
                        payOrder.setDiscountCouponAmt(finalCouponAmount.doubleValue());
                        payOrder.setCouponUserId(couponUser.getCouponUserId().toString());
                        payOrder.setDiscountCoupon(couponUser.getCouponUserId().toString());
                        CouponAmt = CouponAmt.subtract(finalCouponAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
/*                        if(amt.compareTo(BigDecimal.ZERO)<1){
                            amt = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }*/
                        resultMap.put("discountCouponAmt", finalCouponAmount);
                        resultMap.put("discountCoupon", couponUser.getCouponUserId());
                        resultMap.put("discountMaxCoupon", couponUser);
                    }
                }
            }


            if (CouponAmt.compareTo(BigDecimal.ZERO) < 1) {
                BigDecimal aaacouponAmt = new BigDecimal(0.01);
                CouponAmt = aaacouponAmt.setScale(2, RoundingMode.HALF_UP);

            }
            //之前查询的oilperson做转译了，现在置空不进行更新
            payOrder.setOilPersonnel(null);
            //之前查询的oilname做转译了，现在置空不进行更新
            payOrder.setOilName(null);
            payOrder.setAmt(CouponAmt.doubleValue());
            // payOrder.setDiscountCouponAmt(couponAmount.doubleValue());
            if (reductionAmount.compareTo(BigDecimal.ZERO) < 1) {
                payOrder.setActivityDeleteFalg("1");
                payOrder.setDiscountAmt(null);
                payOrder.setDicountAmtDeleteFalg("1");
            } else {
                payOrder.setDiscountAmt(reductionAmount.doubleValue());
            }

            // 不加渠道费的实付金额
            BigDecimal oriAmt = CouponAmt;
            // 计算渠道费
            calculateChannelFee(CouponAmt, payOrder, request, resultMap);

//            BigDecimal bigDecimalValue = BigDecimal.valueOf(payOrder.getAmt());
//            if(bigDecimalValue.compareTo(new BigDecimal(0.01)) == 0){
//                Map<String, Object> map2=null;
//                if (request.getPayType().equals("wx")) {
//                    map2 = payOrderMapper.selectServiceCharge(request.getStationId(),1);
//                }else if (request.getPayType().equals("zfb")){
//                    map2 = payOrderMapper.selectServiceCharge(request.getStationId(),2);
//                }
//                if(Objects.nonNull(map2) &&  Objects.nonNull(map2.get("serviceCharge"))){
//                    payOrder.setAmt(0.02);
//                    payOrder.setCommission(0.01);
//                    CouponAmt = new BigDecimal(0.02);
//                    resultMap.put("channelFeePayer", 0.01);
//                }
//            }
            resultMap.put("finalAmount", payOrder.getReceivableAmt());
            payOrderMapper.updateByPrimaryKeySelective(payOrder);
            CouponAmt = BigDecimal.valueOf(payOrder.getAmt());
            //优惠价格
            BigDecimal discountPrice = amt.divide(new BigDecimal(payOrder.getOrderLiters()), 2, BigDecimal.ROUND_HALF_UP);
            resultMap.put("discountPrice", discountPrice);                      //优惠价格
            resultMap.put("discountAmt", reductionAmount.setScale(2, BigDecimal.ROUND_HALF_UP));                      //优惠金额
            resultMap.put("isShowPaymentCommission",station.getIsShowPaymentCommission());
            if (station.getIsShowPaymentAmtCommission()==0) {
                resultMap.put("amt",oriAmt.setScale(2,RoundingMode.HALF_UP));
            }else{
                resultMap.put("amt", CouponAmt.setScale(2, BigDecimal.ROUND_HALF_UP));                                          //实收金额
            }
            resultMap.put("dzkAmt", CouponAmt.setScale(2, BigDecimal.ROUND_HALF_UP));                                       //电子卡支付金额
            resultMap.put("receivableAmt", payOrder.getReceivableAmt()); //应收金额
            resultMap.put("oilLiters", payOrder.getOrderLiters());                              //加油升数
            resultMap.put("ordNo", payOrder.getOrderNo());                                      //订单号
            resultMap.put("cardType", staOilGun.getOil().getCardType());    //该油品对应的电子卡类型

            logger.info("/updateOrderByCoupon-" + payOrder.getOrderNo() + "--返回前端的结果:" + resultMap.toString());

            return ResultData.successJson(resultMap);

        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/createOrder-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }
    }


    // 计算渠道费
    private void calculateChannelFee(BigDecimal amt, PayOrder payOrder, PayOrderRequest request, Map<String, Object> resultMap) {
        PayWay payWay = null;
        if (StringUtils.equals("1", request.getCardFlag()) // 判断是不是电子卡，1-不是电子卡支付，2-是电子卡支付
                && StringUtils.equalsAny(request.getPayType(), "wx", "zfb") // 是不是微信，支付宝
        ) {
            // 微信、支付宝才计算渠道费
            PayWay payWayForm = new PayWay();
            payWayForm.setUseType(String.valueOf(PayWayUseTypeEnum.CONSUME.getValue()));
            payWayForm.setStationId(payOrder.getStationId());
            if (StringUtils.equals("wx", request.getPayType())) {
                payWayForm.setAppType(String.valueOf(PayWayServiceChargeEnum.APPTYPE_WECHAT.getValue()));
            } else if (StringUtils.equals("zfb", request.getPayType())) {
                payWayForm.setAppType(String.valueOf(PayWayServiceChargeEnum.APPTYPE_ALIPAY.getValue()));
            }
            payWay = payWayMapper.getOneStationPayWay(payWayForm);
            if (Objects.nonNull(payWay) && Objects.nonNull(payWay.getServiceCharge())) {
                payOrder.setPayWayId(payWay.getPayWayId());
                payOrder.setServiceCharge(payWay.getServiceCharge());
                payOrder.setChannelFeePayer(payWay.getChannelFeePayer());
                if (amt.compareTo(DecimalConstant.O_01) <= 0) {
                    //金额小于等于0.01不计算渠道费
                    payOrder.setCommission(0d);
                    return;
                }
                if (StringUtils.equals("0", payWay.getChannelFeePayer())) {
                    //司机承担
                    BigDecimal serviceCharge = payWay.getServiceCharge().multiply(DecimalConstant.O_001);
                    //司机支付的通道费
                    BigDecimal driverCommission = serviceCharge.multiply(amt).setScale(2, RoundingMode.HALF_UP);
                    //最终价格
                    amt = amt.add(driverCommission).setScale(2, RoundingMode.HALF_UP);
                    //油企支付的通道费
                    BigDecimal commission = amt.multiply(serviceCharge).setScale(2, RoundingMode.HALF_UP);
                    resultMap.put("channelFeePayer", driverCommission);
                    payOrder.setAmt(amt.doubleValue());
                    payOrder.setDzkAmt(amt.doubleValue());
                    payOrder.setCommission(commission.doubleValue());
                } else {
                    //油企承担
                    BigDecimal serviceCharge = payWay.getServiceCharge();
                    resultMap.put("channelFeePayer", 0);
                    //渠道费
                    BigDecimal commission = serviceCharge.multiply(DecimalConstant.O_001).multiply(amt).setScale(2, RoundingMode.HALF_UP);
                    payOrder.setCommission(commission.doubleValue());
                }
            } else {
                // 找到payWay但是费率为null，也把payWay改为null
                payWay = null;
            }
        }
        if (payWay == null) {
            // 不是微信、支付宝或者payWay找不到时，设置渠道费为0
            payOrder.setServiceCharge(BigDecimal.ZERO);
            payOrder.setCommission(0d);
            resultMap.put("channelFeePayer", 0);
            payOrder.setChannelFeePayer("1");
            payOrder.setPayWayId(null);
        }
    }


    private String generateOrdNo() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        return ordNo;
    }

    private void checkOrderRandomId(PayOrderRequest request) throws EndingException {
        PayOrder duplicateOrder = payOrderService.selectPosPayOrderInfoByOrderRandomId(request.getOrderRandomId());
        if (duplicateOrder != null) {
            logger.info("/createOrder-" + request.getMobilePhone() + "--出现重复的随机码:" + duplicateOrder.getOrderRandomId());
            //POS机扫码下订单根据随机数查询，如果有，则表示该二维码已被扫用；
            Boolean flag = duplicateOrder.getCustomerPhone().equals(request.getMobilePhone())
                    && duplicateOrder.getAppType().equals(request.getAppType())
                    && duplicateOrder.getPayType().equals(request.getPayType())
                    && duplicateOrder.getOrderOriginType().equals(request.getOrderOriginType())
                    && duplicateOrder.getStationId() == request.getStationId()
                    && duplicateOrder.getOilPersonnelId().equals(request.getUserId())
                    && (new BigDecimal(duplicateOrder.getReceivableAmt())).setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(new BigDecimal(request.getReceivableAmt()).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0
                    && "0".equals(duplicateOrder.getStatus());
            if (!flag) {
                // 前端根据8 来提示扫码
                throw new EndingException(-8, "二维码已经被扫用");
            }

            int delCount = payOrderMapper.delOldRandomId(request.getOrderRandomId());

            if (delCount == 0) {
                // 前端根据8 来提示扫码
                throw new EndingException(-8, "二维码已经被扫用");
            }

        }
    }

    //获取电子卡余额
/*    public CustomerElectronicCard getCustomerElectronicCard(AppUserInfo appUserInfos, String cardType){
        logger.info("查询用户电子卡参数：油站ID：" + appUserInfos.getStationId() + "卡类型：" + cardType + "手机号：" + appUserInfos.getMobilePhone());
        CustomerElectronicCard electronicCardInfoByPhone
                = electronicMembershipCardService.getElectronicCardInfoByPhone(CustomerElectronicCard.builder()
                .stationId(appUserInfos.getStationId())
                .cardOilsType(cardType)
                .mobilePhone(appUserInfos.getMobilePhone()).build());
        if(null != electronicCardInfoByPhone){
            //存在
            return electronicCardInfoByPhone;
        }else {
            //不存在
            CustomerElectronicCard ces = new CustomerElectronicCard();
            ces.setCreateTime(new Date());
            ces.setAmt(BigDecimal.ZERO);
            ces.setCardOilsType(cardType);
            ces.setCustomerNo(appUserInfos.getMemberCode());
            ces.setMobilePhone(appUserInfos.getMobilePhone());
            ces.setStationId(appUserInfos.getStationId());
            electronicMembershipCardService.insetElectronicCard(ces);
            return electronicMembershipCardService.getElectronicCardInfoByPhone(CustomerElectronicCard.builder()
                    .stationId(appUserInfos.getStationId())
                    .cardOilsType(cardType)
                    .mobilePhone(appUserInfos.getMobilePhone()).build());
        }
    }*/

    /*
     * 小程序消费支付拉起第三方支付
     * @param payInfoRequest
     * @return
     */
    @ApiOperation(value = "消费支付拉起第三方支付", httpMethod = "POST", notes = "消费支付拉起第三方支付")
    @PostMapping(value = "/toThirdPay")
    @Transactional
    public String toThirdPay(@RequestBody PayInfoRequest payInfoRequest) {

        try {
            if (StringUtils.isBlank(payInfoRequest.getStationId()) || StringUtils.isBlank(payInfoRequest.getOrdNo())) {
                throw new EndingException("缺少必传参数");
            }
            if (StringUtils.isBlank(payInfoRequest.getOpenId()) && StringUtils.isBlank(payInfoRequest.getAliUserId())) {
                throw new EndingException("缺少用户参数");
            }

            String stationId = payInfoRequest.getStationId();
            String ordNo = payInfoRequest.getOrdNo();
            String openId = "";

            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (payOrder == null) {
                throw new EndingException("查无此单");
            }
            if (payOrder.getStatus() == null || !payOrder.getStatus().equals("0")) {
                throw new EndingException("订单状态不对");
            }

            String payType = payOrder.getPayType();       //用户类型：1、微信；2、支付宝；
//            String orderOriginType = payOrder.getOrderOriginType();     //订单来源：1、微信小程序；2、微信公众号；3、支付宝小程序；4、支付宝公众号；
            //获取油站的支付配置项信息
            String payType_num = "";
            PayWay payWay = new PayWay();
            payWay.setStationId(Integer.valueOf(stationId));

            switch (payType) {
                case "wx":   //微信
                    payType_num = "1";
                    openId = payInfoRequest.getOpenId();
                    break;
                case "zfb":  //支付宝
                    payType_num = "2";
                    openId = payInfoRequest.getAliUserId();
                    break;
                case "yl":   //银联
                    payType_num = "3";
                    break;
            }

            payWay.setAppType(payType_num);        //支付宝还是微信
            payWay.setUseType("1");             //使用类型
            List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay); //获取该油站的支付类型
            HashMap<String, Object> resultMap = new HashMap<>();
            if (payWayList == null && payWayList.size() != 1) {
                throw new EndingException("支付渠道数目不对");
            }
            PayOrder p = new PayOrder();                            //更新订单参数
            String amt = payOrder.getAmt().toString();              //订单实付金额

            // 优惠券逻辑
            if (StringUtils.isNotBlank(payInfoRequest.getCouponUserId())) {
                logger.info("/toThirdPay-CouponUserId：" + payInfoRequest.getCouponUserId());

                Station station = enterpriseService.selectStationById(Integer.valueOf(payOrder.getStationId()));
                AppUserInfo appUserInfo = appUserInfoService.getById(payOrder.getConsumerId());

                //计算使用优惠券后传参优惠券ID
                payOrder.setDiscountCoupon(payInfoRequest.getCouponUserId());
                //计算优惠券
                CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrder, station);

                logger.info("/toThirdPay-couponUser：" + couponUser);
                if (couponUser != null) {
                    //使用优惠券时要更新的订单信息
                    amt = couponUser.getNewAmtByCoupon().toString();
                    p.setDiscountCoupon(payInfoRequest.getCouponUserId());
                    p.setDiscountCouponAmt(couponUser.getCouponAmtByCNY().doubleValue());
                    p.setAmt(Double.valueOf(amt));
                    logger.info("/toThirdPay-使用优惠券后的amt：" + amt);

                }
            }

            String payTypeSta = payWayList.get(0).getPayType();     //第三方支付类型
            String mno = payWayList.get(0).getMno();                //商户号
            String subject = payOrder.getOilName() + " - " + payOrder.getStationName();
            String appId = payWayList.get(0).getEnterprise().getAppId();
            String notifyUrl = "";


            switch (payTypeSta) {
                case "1":   //随行付
                    notifyUrl = "https://" + domainName + contextPath + "/sxfPayCallbackV2";

                    List<DivideAccountsSettingDto> divideAccList =   payOrderMapper.selectDivideSettingDetail(mno,stationId);
//        处理分账
                    String ledgerAccountFlag = "0";
                    if(divideAccList.size()>0 && divideAccList.get(0).getBeginMmo()!=null){
                        ledgerAccountFlag = "1";
                    }
                    resultMap = SXFPayUtil.sxfGoPay(
                            SXFPayParam.builder()
                                    .amt(amt)
                                    .appId(appId)
                                    .mno(mno)
                                    .ordNo(ordNo)
                                    .notifyUrl(notifyUrl)
                                    .subject(subject)
                                    .userId(openId)
                                    .ledgerAccountFlag(ledgerAccountFlag)
                                    .customerIp(payInfoRequest.getCustomerIp())
                                    .ylTrmNo(payInfoRequest.getYlTrmNo())
                                    .userType(payType_num)
                                    .weChatType("1")
                                    .build());
                    break;
                case "2":   //圈圈（元闪付，扫呗）
                    notifyUrl = "https://" + domainName + contextPath + "/sbPayCallback";
                    resultMap = SBPayUtil.saoBeiTradePay(
                            SBPayParam.builder()
                                    .amt(amt)
                                    .appId(appId)
                                    .userType(payType_num)
                                    .appPayType("1")
                                    .key(payWayList.get(0).getSecretKey())
                                    .openId(openId)
                                    .terminalId(payWayList.get(0).getTerminalNo())
                                    .ordNo(ordNo)
                                    .orderBody(subject)
                                    .notifyUrl(notifyUrl)
                                    .merchantNo(mno)
                                    .build());
                    break;
                case "3":   //通联支付
                    long amtLong = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                    //通联智U+，需要实时到账，分账时预支付接口
                    if ("1".equals(payWayList.get(0).getTlFusFlag())) {
                        notifyUrl = "https://" + domainName + contextPath + "/tLFusClassPayCallback";     //回调地址
                        String tlFusClassPayType = "wx".equals(payType) ? "WECHATPAY_MINIPROGRAM" : "ALIPAY_SERVICE";
                        logger.info("payway支付参数信息：" + payWayList.get(0).getPayWayId());
                        //获取通联支付的班次标识
                        String shiftsMask = "";
                        String shiftsTime = "";
                        Map<String, String> smat = this.getShiftsMaskAndTime(payWayList.get(0).getPayWayId());
                        if (null != smat && smat.containsKey("shiftsMask") && smat.containsKey("shiftsTime")) {
                            shiftsMask = smat.get("shiftsMask");
                            p.setTlShiftsMask(shiftsMask);
                            shiftsTime = smat.get("shiftsTime");
                            p.setTlShiftsTime(shiftsTime);
                        } else {
                            logger.info("未设置班次");
                        }
                        logger.info("班次标识：" + shiftsMask + "; 班次时间：" + shiftsTime);
                        resultMap = TLFusClassPayUtil.tLFusClassPayApply(
                                TLFusClassPayParam.builder()
                                        .account(openId)                        //oWL5P5PPF5gFmoDid19Ij_nN5h70  openId oRwjv4iHjSUgxNxOJOQ_60Ln7cno
                                        .amount(amtLong)
                                        .backUrl(notifyUrl)
                                        .bizOrderNo(ordNo)
                                        .sysId(payWayList.get(0).getTlSysId())
                                        .tlAppId(payWayList.get(0).getTlAppId())
                                        .tlAppKey(payWayList.get(0).getTlAppKey())
                                        .tlOilStationNo(payWayList.get(0).getTlOilStationNo())                 //通联支付所需要的油站编码
                                        .consumeType("C0001")                                                  //消费类型
                                        .shiftsMask(shiftsMask)                                                //班次标识
                                        .shiftsTime(shiftsTime)     //班次时间
                                        .remark(subject)
                                        .subAppId(appId)                            //wxb46701bd193ee573 appId wxe1135cd390b38a54
                                        .payType(tlFusClassPayType)
                                        .build());
                    } else {
                        //通联收银宝预支付接口
                        notifyUrl = "https://" + domainName + contextPath + "/tLPayCallback";
                        String tlPayType = "wx".equals(payType) ? "W06" : "A02";
                        resultMap = TLPayUtil.tLTradePay(
                                TLPayParam.builder()
                                        .body(subject)
                                        .notifyUrl(notifyUrl)
                                        .remark(subject)
                                        .reqSn(ordNo)
                                        .payType(tlPayType)
                                        .acct(openId)                                               //微信用户openId
                                        .subAppId(appId)                                            //微信appId
                                        .sybAppId(payWayList.get(0).getAllinpayAppId())             //通联系统分配的appId 00226421 payWayList.get(0).getAllinpayAppId()
                                        .SIGN_TYPE("RSA")                                       //通联验签加密方式  RSA； SM2； MD5；
                                        .SYB_RSACUSPRIKEY(payWayList.get(0).getAllinpayRSAKey())    //秘钥 RSA； SM2； MD5；
                                        .cusId(mno)                                                 //商户号
                                        .trxAmt(amtLong)                                            //单位分
                                        .build());
                    }
                    break;
                case "4":   //金控支付
                    notifyUrl = "https://" + domainName + contextPath + "/JKNotice";
                    long amtLong1 = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                    resultMap = JKPayUtil.JKPay(JKPayParam.builder()
                            .merchantNo(payWayList.get(0).getMno())
                            .orderNo(ordNo)
                            .notifyUrl(notifyUrl)
                            .amt(amtLong1 + "")
                            .appId(appId)
                            .openId(openId)
                            .private_pfxPath(private_pfxPath)
                            .public_certPath(public_certPath)
                            .buyerId(openId)
                            .payChannelCode(payType_num)
                            .build());
                    break;
            }

            resultMap.put("thirdPayment", payTypeSta);
            p.setOrderNo(payInfoRequest.getOrdNo());
            p.setServiceCharge(payWayList.get(0).getServiceCharge());       //费率
            p.setPayWayId(payWayList.get(0).getPayWayId());                 //第三方支付类型
            if (resultMap.containsKey("merchantsNumber")) {
                p.setMerchantsNumber(resultMap.get("merchantsNumber").toString());
            }
            payOrderService.getUpdatePayOrder(p);
            return ResultData.successJson(resultMap);


        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/toThirdPay-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }

    }


    /*
     * 小程序消费支付拉起第三方支付
     * @param payInfoRequest
     * @return
     */
    @ApiOperation(value = "消费支付拉起第三方支付", httpMethod = "POST", notes = "消费支付拉起第三方支付")
    @PostMapping(value = "/toThirdPayV2")
    @Transactional
    public String toThirdPayV2(@RequestBody PayInfoRequest payInfoRequest) {
        log.info("拉起支付参数payInfoRequest{}", payInfoRequest.toString());
        try {
            if (StringUtils.isBlank(payInfoRequest.getStationId()) || StringUtils.isBlank(payInfoRequest.getOrdNo())) {
                throw new EndingException("缺少必传参数");
            }
            if (StringUtils.isBlank(payInfoRequest.getOpenId()) && StringUtils.isBlank(payInfoRequest.getAliUserId())) {
                throw new EndingException("缺少用户参数");
            }

            String stationId = payInfoRequest.getStationId();
            String ordNo = payInfoRequest.getOrdNo();
            String openId = "";


            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (payOrder == null) {
                throw new EndingException("查无此单");
            }
            if (payOrder.getStatus() == null || !payOrder.getStatus().equals("0")) {
                throw new EndingException("订单状态不对");
            }

            /*String userId="";
            List<AppUserInfo>appUserInfos=appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(AppUserInfo.builder().mobilePhone(payOrder.getCustomerPhone()).stationId(payOrder.getEnterpriseId()).build());
           if(appUserInfos!=null&&appUserInfos.size()>0){
               if(appUserInfos.get(0).getYunhuaUserId()!=null){
                   userId=appUserInfos.get(0).getYunhuaUserId();
               }else {
                   userId=appUserInfos.get(0).getMobilePhone();
               }
           }*/
            AppUserInfo appUserInfo = appUserInfoService.getById(payOrder.getConsumerId());
            String userId = null;
            if (StringUtils.isNotBlank(appUserInfo.getYunhuaUserId())) {
                userId = appUserInfo.getYunhuaUserId();
            } else if (!MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone())) {
                userId = appUserInfo.getMobilePhone();
            } else {
                userId = YunhuaChannel.DEFAULT_USER_ID;
            }
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(payOrder.getEnterpriseId());
            String payType = payOrder.getPayType();       //用户类型：1、微信；2、支付宝；
//            String orderOriginType = payOrder.getOrderOriginType();     //订单来源：1、微信小程序；2、微信公众号；3、支付宝小程序；4、支付宝公众号；
            //获取油站的支付配置项信息
            String payType_num = "";
            PayWay payWay = new PayWay();
            payWay.setStationId(Integer.valueOf(stationId));
            String payAppId = "";
            if ("wx".equals(payOrder.getPayType())) {
                if ("1".equals(payOrder.getOrderOriginType())) {
                    payAppId = enterprise.getAppId();
                }
                if ("2".equals(payOrder.getOrderOriginType())) {
                    payAppId = enterprise.getGzhAppId();
                }
            }

            switch (payType) {
                case "wx":   //微信
                    payType_num = "1";
                    openId = payInfoRequest.getOpenId();
                    break;
                case "zfb":  //支付宝
                    payType_num = "2";
                    openId = payInfoRequest.getAliUserId();
                    break;
                case "yl":   //银联
                    payType_num = "3";
                    break;
            }

            payWay.setAppType(payType_num);        //支付宝还是微信
            payWay.setUseType("1");             //使用类型
            List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay); //获取该油站的支付类型
            HashMap<String, Object> resultMap = new HashMap<>();
            if (payWayList == null && payWayList.size() != 1) {
                throw new EndingException("支付渠道数目不对");
            }
            PayOrder p = new PayOrder();                            //更新订单参数
            String amt = payOrder.getAmt().toString();              //订单实付金额

            // 优惠券逻辑
            if (!MobilePhoneUtil.isFakePhone(payOrder.getCustomerPhone()) && StringUtils.isNotBlank(payInfoRequest.getCouponUserId())) {
                logger.info("/toThirdPay-CouponUserId：" + payInfoRequest.getCouponUserId());

                Station station = enterpriseService.selectStationById(Integer.valueOf(payOrder.getStationId()));

                //计算使用优惠券后传参优惠券ID
                payOrder.setDiscountCoupon(payInfoRequest.getCouponUserId());
                //计算优惠券
                CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrder, station);

                if (couponUser != null) {
                    //使用优惠券时要更新的订单信息
                    //amt = couponUser.getNewAmtByCoupon().toString();
                    p.setDiscountCoupon(payInfoRequest.getCouponUserId());
                    p.setDiscountCouponAmt(payOrder.getReceivableAmt() - payOrder.getAmt() - payOrder.getDiscountAmt());

                }

            }

            String payTypeSta = payWayList.get(0).getPayType();     //第三方支付类型
            String mno = payWayList.get(0).getMno();                //商户号
            String subject = payOrder.getOilName() + " - " + payOrder.getStationName();
            String appId = payWayList.get(0).getEnterprise().getAppId();
            String notifyUrl = "";
            String weChatType = "2";
            if (payInfoRequest.getPayAppType() != null && !"".equals(payInfoRequest.getPayAppType()) && "1".equals(payInfoRequest.getPayAppType())) {
                weChatType = "1";
            }

            log.info("wetchatType---------------------------" + weChatType);
            switch (payTypeSta) {
                case "1":   //随行付
                    notifyUrl = "https://" + domainName + contextPath + "/sxfPayCallbackV2";
                    List<DivideAccountsSettingDto> divideAccList =   payOrderMapper.selectDivideSettingDetail(mno,stationId);
//        处理分账
                    String ledgerAccountFlag = "0";
                    if(divideAccList.size()>0 && divideAccList.get(0).getBeginMmo()!=null){
                        ledgerAccountFlag = "1";
                    }
                    resultMap = SXFPayUtil.sxfGoPay(
                            SXFPayParam.builder()
                                    .amt(amt)
                                    .appId(appId)
                                    .mno(mno)
                                    .ordNo(ordNo)
                                    .notifyUrl(notifyUrl)
                                    .subject(subject)
                                    .userId(openId)
                                    .ledgerAccountFlag(ledgerAccountFlag)
                                    .customerIp(payInfoRequest.getCustomerIp())
                                    .ylTrmNo(payInfoRequest.getYlTrmNo())
                                    .userType(payType_num)
                                    .weChatType(weChatType)
                                    .build());
                    break;
                case "2":   //圈圈（元闪付，扫呗）
                    notifyUrl = "https://" + domainName + contextPath + "/sbPayCallback";
                    resultMap = SBPayUtil.saoBeiTradePay(
                            SBPayParam.builder()
                                    .amt(amt)
                                    .appId(appId)
                                    .userType(payType_num)
                                    .appPayType("1")
                                    .key(payWayList.get(0).getSecretKey())
                                    .openId(openId)
                                    .terminalId(payWayList.get(0).getTerminalNo())
                                    .ordNo(ordNo)
                                    .orderBody(subject)
                                    .notifyUrl(notifyUrl)
                                    .merchantNo(mno)
                                    .build());
                    resultMap.put("payAppId", payAppId);

                    break;
                case "3":   //通联支付
                    long amtLong = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                    //通联智U+，需要实时到账，分账时预支付接口
                    if ("1".equals(payWayList.get(0).getTlFusFlag())) {
                        notifyUrl = "https://" + domainName + contextPath + "/tLFusClassPayCallback";     //回调地址
                        String tlFusClassPayType = "wx".equals(payType) ? "WECHATPAY_MINIPROGRAM" : "ALIPAY_SERVICE";
                        logger.info("payway支付参数信息：" + payWayList.get(0).getPayWayId());
                        //获取通联支付的班次标识
                        String shiftsMask = "";
                        String shiftsTime = "";
                        Map<String, String> smat = this.getShiftsMaskAndTime(payWayList.get(0).getPayWayId());
                        if (null != smat && smat.containsKey("shiftsMask") && smat.containsKey("shiftsTime")) {
                            shiftsMask = smat.get("shiftsMask");
                            p.setTlShiftsMask(shiftsMask);
                            shiftsTime = smat.get("shiftsTime");
                            p.setTlShiftsTime(shiftsTime);
                        } else {
                            logger.info("未设置班次");
                        }
                        logger.info("班次标识：" + shiftsMask + "; 班次时间：" + shiftsTime);
                        resultMap = TLFusClassPayUtil.tLFusClassPayApply(
                                TLFusClassPayParam.builder()
                                        .account(openId)                        //oWL5P5PPF5gFmoDid19Ij_nN5h70  openId oRwjv4iHjSUgxNxOJOQ_60Ln7cno
                                        .amount(amtLong)
                                        .backUrl(notifyUrl)
                                        .bizOrderNo(ordNo)
                                        .sysId(payWayList.get(0).getTlSysId())
                                        .tlAppId(payWayList.get(0).getTlAppId())
                                        .tlAppKey(payWayList.get(0).getTlAppKey())
                                        .tlOilStationNo(payWayList.get(0).getTlOilStationNo())                 //通联支付所需要的油站编码
                                        .consumeType("C0001")                                                  //消费类型
                                        .shiftsMask(shiftsMask)                                                //班次标识
                                        .shiftsTime(shiftsTime)     //班次时间
                                        .remark(subject)
                                        .subAppId(appId)                            //wxb46701bd193ee573 appId wxe1135cd390b38a54
                                        .payType(tlFusClassPayType)
                                        .build());
                        resultMap.put("payAppId", payAppId);
                    } else {
                        //通联收银宝预支付接口
                        notifyUrl = "https://" + domainName + contextPath + "/tLPayCallback";
                        String tlPayType = "wx".equals(payType) ? "W06" : "A02";
                        resultMap = TLPayUtil.tLTradePay(
                                TLPayParam.builder()
                                        .body(subject)
                                        .notifyUrl(notifyUrl)
                                        .remark(subject)
                                        .reqSn(ordNo)
                                        .payType(tlPayType)
                                        .acct(openId)                                               //微信用户openId
                                        .subAppId(appId)                                            //微信appId
                                        .sybAppId(payWayList.get(0).getAllinpayAppId())             //通联系统分配的appId 00226421 payWayList.get(0).getAllinpayAppId()
                                        .SIGN_TYPE("RSA")                                       //通联验签加密方式  RSA； SM2； MD5；
                                        .SYB_RSACUSPRIKEY(payWayList.get(0).getAllinpayRSAKey())    //秘钥 RSA； SM2； MD5；
                                        .cusId(mno)                                                 //商户号
                                        .trxAmt(amtLong)                                            //单位分
                                        .build());
                        resultMap.put("payAppId", payAppId);
                    }
                    break;
                case "4":   //金控支付
                    notifyUrl = "https://" + domainName + contextPath + "/JKNotice";
                    long amtLong1 = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                    resultMap = JKPayUtil.JKPay(JKPayParam.builder()
                            .merchantNo(payWayList.get(0).getMno())
                            .orderNo(ordNo)
                            .notifyUrl(notifyUrl)
                            .amt(amtLong1 + "")
                            .appId(appId)
                            .openId(openId)
                            .private_pfxPath(private_pfxPath)
                            .public_certPath(public_certPath)
                            .buyerId(openId)
                            .payChannelCode(payType_num)
                            .build());
                    resultMap.put("payAppId", payAppId);
                    break;
                case "5":   //云华支付
                    notifyUrl = "https://" + domainName + contextPath + "/yunHuaNotice";
//                    String   payFor="wx_jsapi";
//                    if("wx".equals(payOrder.getPayType())){
//
//                        if("1".equals(payOrder.getOrderOriginType())){
//                            payFor="wx_minipay";
//                        }
//                        if("2".equals(payOrder.getOrderOriginType())){
//                            payFor="wx_jsapi";
//                        }
//
//                    }else if("zfb".equals(payOrder.getPayType())) {
//                        payFor="";
//                    }
//                    String nowdate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//                    resultMap = yunHuaPayUtils.yunHuaPay(YunHuaParam.builder()
//                            .clientOrgCode(payWayList.get(0).getMno())
//                            .lockFlag("lock")
//                            .noticeUrl(notifyUrl)
//                            .partnerCode(payWayList.get(0).getTerminalNo())
//                            .payChannelId(payFor)
//                            .posOrderNo(ordNo)
//                            .reqTime(nowdate)
//                            .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
//                            .vsOrderNo(ordNo)
//                            .openId(openId)
//                            .carRefueling(nowdate)
//                            .build());
//                    resultMap.put("payAppId",payAppId);

//                    notifyUrl = "https://" + domainName + contextPath + "/yunHuaNotice";
                    log.info("weChatType{}", weChatType);
                    String txnDesc = "（未知）";
                    switch (payType) {
                        case "zfb":
                            log.info("支付宝拉起支付");

                            if(payOrder.getOilName()!=null){
                                txnDesc = payOrder.getOilName();
                            }
                            resultMap = yunHuaPayUtils.yunHuaPayAli(YunHuaParam.builder()
                                    .partnerCode(payWayList.get(0).getMno())
                                    .posOrderNo(ordNo)
                                    .openId(openId)
                                    .noticeUrl(notifyUrl)
                                    .txnDesc(txnDesc)
                                    .miniUrl("www.123.com")
                                    .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
                                    .userId(userId)
                                    .build(), payWayList.get(0).getSecretKey(), yunhuaPayUrl);
                            p.setClientOrderNo(resultMap.get("clientOrderNo").toString());
                            p.setClientSerialNo(resultMap.get("clientSerialNo").toString());
                            p.setMno(resultMap.get("mno").toString());
                            break;

                        case "wx":
                            if (weChatType.equals("1")) {
                                //小程序
                                log.info("小程序拉起支付");
                                resultMap = yunHuaPayUtils.yunHuaPayWxMini(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .noticeUrl(notifyUrl)
                                        .miniUrl("www.123.com")
                                        .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
                                        .userId(userId)
                                        .build(), payWayList.get(0).getSecretKey(), yunHuaPrePayUrl);
                                p.setClientOrderNo(resultMap.get("clientOrderNo").toString());
                                p.setClientSerialNo(resultMap.get("clientSerialNo").toString());
                                p.setMno(resultMap.get("mno").toString());
                            } else {
                                log.info("公众号拉起支付");

                                if(payOrder.getOilName()!=null){
                                     txnDesc = payOrder.getOilName();
                                }
                                resultMap = yunHuaPayUtils.yunHuaPayV2(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .noticeUrl(notifyUrl)
                                        .txnDesc(txnDesc)
                                        .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
                                        .userId(userId)
                                        .build(), payWayList.get(0).getSecretKey(), yunHuaPrePayUrl);
                                p.setClientOrderNo(resultMap.get("clientOrderNo").toString());
                                p.setClientSerialNo(resultMap.get("clientSerialNo").toString());
                                p.setMno(resultMap.get("mno").toString());
                            }
                    }
                    resultMap.put("payAppId", payAppId);
                    break;
            }

            
            resultMap.put("thirdPayment", payTypeSta);
            p.setOrderNo(payInfoRequest.getOrdNo());
//            p.setServiceCharge(payWayList.get(0).getServiceCharge());       //费率
            p.setPayWayId(payWayList.get(0).getPayWayId());                 //第三方支付类型
            if (resultMap.containsKey("merchantsNumber")) {
                p.setMerchantsNumber(resultMap.get("merchantsNumber").toString());
            }
            payOrderService.getUpdatePayOrder(p);
            log.info("返回值{}", resultMap);
            return ResultData.successJson(resultMap);


        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/toThirdPay-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }

    }

    /*
     * 小程序消费 通联智U+，需要实时到账，分账时 获取班次时间与班次标识
     * @param payWayId
     * @return
     * @throws ParseException
     */
    public Map<String, String> getShiftsMaskAndTime(Integer payWayId) throws ParseException {
        Map<String, String> resultMap = new HashMap<>();
        if (null != payWayId) {
            String shiftsMask = "";
            String shiftsTime = "";
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            List<ShiftClass> shiftClassList = enterpriseService.selectShiftClassList(ShiftClass.builder().payWayId(payWayId).build());
            if (null != shiftClassList && shiftClassList.size() > 0) {
                for (ShiftClass sc : shiftClassList) {
                    //如果开始时间小于结束时间，做处理
                    if (sc.getShiftStartTime().compareTo(sc.getShiftEndTime()) <= 0) {
                        if (sdf.format(new Date()).compareTo(sc.getShiftStartTime().toString()) >= 0 && sdf.format(new Date()).compareTo(sc.getShiftEndTime().toString()) < 0) {
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                    } else {
                        //否则开始时间大于结束时间
                        if (sdf.format(new Date()).compareTo(sc.getShiftStartTime().toString()) >= 0 && sdf.format(new Date()).compareTo("23:59:59") <= 0) {
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                        if (sdf.format(new Date()).compareTo("00:00:00") >= 0 && sdf.format(new Date()).compareTo(sc.getShiftEndTime().toString()) < 0) {
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = LocalDate.now().plusDays(-1).toString().replace("-", "");
                            break;
                        }
                    }
                }
            }
            logger.info("shiftsMask：" + shiftsMask + "; shiftsTime:" + shiftsTime);
            resultMap.put("shiftsMask", shiftsMask);
            resultMap.put("shiftsTime", shiftsTime);
        }
        return resultMap;
    }

    // 获取当前时间的格式化字符串
    public String getCurrentTime() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置时区为北京时间
        return sdf.format(now);
    }

    // 获取当前时间的 Date 对象
    public Date getCurrentDate() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置时区为北京时间
            return sdf.parse(getCurrentTime());
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "支付成功修改优惠卷状态", httpMethod = "POST", notes = "修改优惠卷状态")
    @PostMapping(value = "/updateCouponUser")
    public ResultData updateCouponUser(@RequestBody CouponUser couponUserId) {
        log.info("/updateCouponUser-" + couponUserId);
        couponUserId.setCouponIsUsed("1");
        couponUserId.setCouponIsEffective("0");
        couponUserId.setVerificationTime(getCurrentDate());
        int i = 0;
        if (Objects.nonNull(couponUserId.getCouponUserId())) {
            i = couponService.updateCouponUser(couponUserId);
        }
        log.info("进来修改了---------------------------" + couponUserId.getCouponUserId());
        if (i <= 0) {
            return ResultData.error(CodeMsg.UPDATE_FAIL);
        }
        return ResultData.success();
    }


    /**
     * 通联 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     *
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request) {
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for (Object key : reqMap.keySet()) {
            String value = ((String[]) reqMap.get(key))[0];
            //System.out.println(key+";"+value);
            map.put(key.toString(), value);
        }
        return map;
    }


    /****
     * 计算积分
     * @return
     */
    public CalculateIntegral calUserIntegral(CalculateIntegral calculateIntegral) {
        int integral = 0;        //普通积分
        int growValue = 0;       //成长值
        int cashIntegral = 0;    //现金积分
        IntegralRule integralRule = new IntegralRule();
        integralRule.setStationId(calculateIntegral.getEnterpriseId());
        integralRule.setOilId(calculateIntegral.getOilId());
        //获取该油站的积分规则
        List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
        if (integralRuleList != null && integralRuleList.size() > 0) {
//            logger.info("该油站积分规则信息：" + integralRuleList.toString());
            Date emptyDate = integralRuleList.get(0).getEmptyDate();
            //积分规则有效时间 为null时 表示永久有效
            if (emptyDate == null || emptyDate.compareTo(new Date()) == 1 || emptyDate.compareTo(new Date()) == 0) {
                List<IntegralRuleDetail> integralRuleDetailList = integralRuleList.get(0).getIntegralRuleDetailList();
                integralRuleDetailList=integralRuleDetailList.stream().filter(i->integralRuleService.checkEffectiveTime(i)).collect(Collectors.toList());
                String currentTime = null;          //当前时间
                String datePickerTime = null;         //活动时间
                String[] datePickerTimeArray = {};
                String integralActivity = integralRuleList.get(0).getIntegralActivity();
                String integralProportion = null;
                if (integralActivity != null && integralActivity.equals("1")) {
                    datePickerTime = integralRuleList.get(0).getDatePickerTime();
                    integralProportion = integralRuleList.get(0).getIntegralProportion();
                    if (datePickerTime.contains(",")) {
                        datePickerTimeArray = datePickerTime.split(",");
                    } else {
                        datePickerTimeArray = new String[1];
                        datePickerTimeArray[0] = datePickerTime;
                    }
                }
                if (integralRuleDetailList != null && integralRuleDetailList.size() > 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());   //获取当前时间
                    BigDecimal multiplyGrowValue = BigDecimal.ZERO;
                    BigDecimal multiplyCashIntegral = BigDecimal.ZERO;
                    for (IntegralRuleDetail integralRuleDetail : integralRuleDetailList) {
                        if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("1")) {  //按照实收金额
                            if (calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0) {
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){      //等级为0时，表示所有人
                                divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                                //BigDecimal multiplyGrowValue = BigDecimal.ZERO;
                                if (integralRuleDetail.getGrowValue() != null) {
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if (null != integralRuleDetail.getCashIntegral()) {
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if (integralActivity != null && integralActivity.equals("1") && datePickerTimeArray != null && integralProportion != null) {
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker) {
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week = day_Week - 1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":   //  2.每月的多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month - 1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                            break;
                                    }
                                    for (String s : datePickerTimeArray) {
                                        if (s.equals(currentTime)) {
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        } else if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("2")) {    //按应收金额
                            if (calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0) {
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){
                                divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());

                                if (integralRuleDetail.getGrowValue() != null) {
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if (null != integralRuleDetail.getCashIntegral()) {
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if (integralActivity != null && integralActivity.equals("1") && datePickerTimeArray != null && integralProportion != null) {
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker) {
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week = day_Week - 1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":   //  2.每月的 多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month - 1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                                            break;
                                    }
                                    for (String s : datePickerTimeArray) {
                                        if (s.equals(currentTime)) {
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        } else if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("3")) {    //按照加油升数
                            if (calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) == 0) {
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){
                                divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                                if (integralRuleDetail.getGrowValue() != null) {
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if (null != integralRuleDetail.getCashIntegral()) {
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if (integralActivity != null && integralActivity.equals("1") && datePickerTimeArray != null && integralProportion != null) {
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker) {
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week = day_Week - 1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":  //  2.每月的 多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month - 1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                                            break;
                                    }
                                    for (String s : datePickerTimeArray) {
                                        if (s.equals(currentTime)) {
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        }
                    }
                }
            }
        }
        // 超级会员的逻辑 这里不对呀
        if (null != calculateIntegral.getUserId()) {
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                    .userId(Long.valueOf(calculateIntegral.getUserId()))
                    .enterpriseId(Long.valueOf(calculateIntegral.getEnterpriseId()))
                    .build());
            if (appUserSuperDetails != null && appUserSuperDetails.size() == 1) {
                AppUserSuperDetail appUserSuperDetail = appUserSuperDetails.get(0);
                if (appUserSuperDetail.getBeginDate() != null && appUserSuperDetail.getBeginDate().before(new Date()) && appUserSuperDetail.getEndDate() != null && appUserSuperDetail.getEndDate().after(new Date())) {
                    AppUserSuper appUserSuper = appUserSuperService.selectAppUserSuperById(appUserSuperDetail.getSuperId());
                    if (appUserSuper != null && null != appUserSuper.getMultiple()) {
                        BigDecimal superIntegral = new BigDecimal(integral).multiply(new BigDecimal(appUserSuper.getMultiple().toString()));
                        integral = superIntegral.setScale(0, BigDecimal.ROUND_UP).intValue();
                    }
                }
            }
        }
        calculateIntegral.setIntegral(integral);
        calculateIntegral.setCashIntegral(cashIntegral);
        calculateIntegral.setGrowValue(growValue);
        logger.info("本次客户所得积分：" + integral);
        logger.info("本次客户所得现金积分：" + cashIntegral);
        logger.info("本次客户所得成长值：" + cashIntegral);
        return calculateIntegral;
    }

    /***
     * 生成积分记录
     * @param calculateIntegral
     */
    public void createIntegralRecord(CalculateIntegral calculateIntegral, String payType, Integer totalIntegral) {
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setCreateTime(new Date());
        if ("xj".equals(payType)) {
            customerPointsRecord.setIntegral(calculateIntegral.getCashIntegral());
        } else {
            customerPointsRecord.setIntegral(calculateIntegral.getIntegral());
        }
        customerPointsRecord.setOrderNo(calculateIntegral.getOrderNo());
        customerPointsRecord.setRecordType("+");
        customerPointsRecord.setMobilePhone(calculateIntegral.getMobilePhone());
        customerPointsRecord.setUnionId(calculateIntegral.getUnionId());
        customerPointsRecord.setStationId(calculateIntegral.getStationId());
        customerPointsRecord.setCustomerName(calculateIntegral.getNickName());
        customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);
        customerPointsRecordService.sendwxgzh(calculateIntegral.getStationId(), calculateIntegral.getMobilePhone(), customerPointsRecord.getIntegral(), totalIntegral, "+");

        logger.info("生成积分记录" + customerPointsRecord.toString());
    }


    /*
     * 小程序消费  随行付异步回调通知
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/sxfPayCallbackV2", consumes = "application/json", method = RequestMethod.POST)
    public String sxfPayCallbackV2(@RequestBody JSONObject request) throws ParseException {
        logger.info("/sxfPayCallbackV2-ordNo" + "" + request.get("ordNo").toString() + "--随行付入参--全部:" + request);
//        JSONObject resultJson = new JSONObject();
//
//        resultJson.put("code", "success");
//        resultJson.put("msg", "成功");
        JSONObject reqData = new JSONObject(); //将业务参数存放在 JSON 对象中

        //*********************************** 必返回参数 *******************************************//
        //String origOrdNo=request.get("origOrdNo").toString();//反交易退款异步通知
        //String origUuid=request.get("origUuid").toString();//token
        //String scene=request.get("scene").toString();//用户登录
        //String buyerAccount=request.get("buyerAccount").toString();//
        //String realRefundAmount=request.get("realRefundAmount").toString();//商家出账金额
        //String recFeeAmt=request.get("recFeeAmt").toString();//交易手续费
        //String recFeeRate=request.get("recFeeRate").toString();//交易手续费率
        //String refBuyerAmt=request.get("refBuyerAmt").toString();//消 费 者 到 账金额
        //String extend = extend=request.get("extend").toString();//备用


        //随行付落单号
        if (request.containsKey("sxfUuid") && request.get("sxfUuid") != null) {
            String sxfUuid = request.get("sxfUuid").toString();
            reqData.put("sxfUuid", sxfUuid);
        }


        String payWay = request.get("payWay").toString();                 //随行付交易方式
        reqData.put("payWay", payWay);


        String payTime = request.get("payTime").toString();               //随行付交易时间
        reqData.put("payTime", payTime);

        String uuid = request.get("uuid").toString();                     //随行付交易流水号
        reqData.put("uuid", uuid);

        String mno = request.get("mno").toString();                       //发起交易的商户编号
        reqData.put("mno", mno);

        String ordNo = request.get("ordNo").toString();                   //商户生成的订单号
        reqData.put("ordNo", ordNo);

        String amt = request.get("amt").toString();                       //金额
        reqData.put("amt", amt);

        String payType = request.get("payType").toString();               //对订单的描述，取值范围：WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
        reqData.put("payType", payType);

        //用户登录
        if (request.containsKey("buyerId") && request.get("buyerId") != null) {
            String buyerId = request.get("buyerId").toString();               //用户登录
            reqData.put("buyerId", buyerId);
        }


        String transactionId = "";
        if (request.containsKey("transactionId") && request.get("transactionId") != null) {
            transactionId = request.get("transactionId").toString();               //用户登录
            reqData.put("transactionId", transactionId);
        }

        if (request.containsKey("drType") && request.get("drType") != null) {
            String drType = request.get("drType").toString();               //借贷记标识 1-借,2-贷，3-其他
            reqData.put("drType", drType);
        }

        if (request.containsKey("pointAmount") && request.get("pointAmount") != null) {
            String pointAmount = request.get("pointAmount").toString();               //代金券金额
            reqData.put("pointAmount", pointAmount);
        }

        if (request.containsKey("payBank") && request.get("payBank") != null) {
            String payBank = request.get("payBank").toString();               //付款银行银行编码，例如 ICBC
            reqData.put("payBank", payBank);
        }

        if (request.containsKey("totalOffstAmt") && request.get("totalOffstAmt") != null) {
            String totalOffstAmt = request.get("totalOffstAmt").toString();               //消 费 者 付 款金额
            reqData.put("totalOffstAmt", totalOffstAmt);
        }

        String settleAmt = request.get("settleAmt").toString();           //商家入账金额
        reqData.put("settleAmt", settleAmt);

        if (request.containsKey("timeStamp") && request.get("timeStamp") != null) {
            String timeStamp = request.get("timeStamp").toString();           //响应时间
            reqData.put("timeStamp", timeStamp);
        }


        String sign = request.get("sign").toString();                     //签名

        if (request.containsKey("bizCode") && request.get("bizCode") != null) {
            String bizCode = request.get("bizCode").toString();               //业务返回码
            reqData.put("bizCode", bizCode);
        }
        if (request.containsKey("bizMsg") && request.get("bizMsg") != null) {
            String bizMsg = request.get("bizMsg").toString();               //业 务 返 回 信息
            reqData.put("bizMsg", bizMsg);
        }
        if (request.containsKey("openid") && request.get("openid") != null) {
            String openid = request.get("openid").toString();               //微 信 或 支 付宝身份id()opendid userid
            reqData.put("openid", openid);
        }
        if (request.containsKey("channelId") && request.get("channelId") != null) {
            String channelId = request.get("channelId").toString();               //渠道商户号
            reqData.put("channelId", channelId);
        }
        if (request.containsKey("subMechId") && request.get("subMechId") != null) {
            String subMechId = request.get("subMechId").toString();               //子商户号
            reqData.put("subMechId", subMechId);
        }
        if (request.containsKey("finishTime") && request.get("finishTime") != null) {
            String finishTime = request.get("finishTime").toString();               //交易完成时间
            reqData.put("finishTime", finishTime);
        }
        if (request.containsKey("clearDt") && request.get("clearDt") != null) {
            String clearDt = request.get("clearDt").toString();
            reqData.put("clearDt", clearDt);
        }
        if (request.containsKey("settlementBatchNo") && request.get("settlementBatchNo") != null) {
            String settlementBatchNo = request.get("settlementBatchNo").toString();
            reqData.put("settlementBatchNo", settlementBatchNo);
        }

        //支付场景
        if (request.containsKey("scene") && request.get("scene") != null) {
            String scene = request.get("scene").toString();
            reqData.put("scene", scene);
        }

        //recFeeRate
        if (request.containsKey("recFeeRate") && request.get("recFeeRate") != null) {
            String recFeeRate = request.get("recFeeRate").toString();
            reqData.put("recFeeRate", recFeeRate);
        }

        //消 费 者 到 账金额
        if (request.containsKey("refBuyerAmt") && request.get("refBuyerAmt") != null) {
            String refBuyerAmt = request.get("refBuyerAmt").toString();
            reqData.put("refBuyerAmt", refBuyerAmt);
        }

        //buyerAccount 支付宝买家登录账号  掩码；示例：135***1234
        if (request.containsKey("buyerAccount") && request.get("buyerAccount") != null) {
            String buyerAccount = request.get("buyerAccount").toString();
            reqData.put("buyerAccount", buyerAccount);
        }

        //备用
        if (request.containsKey("extend") && request.get("extend") != null) {
            String extend = request.get("extend").toString();
            reqData.put("extend", extend);
        }

        //优惠券参数
        if (request.containsKey("promotionDetail") && request.get("promotionDetail") != null) {
            String promotionDetail = request.get("promotionDetail").toString();
            reqData.put("promotionDetail", promotionDetail);
        }
        //商家出账金额
        if (request.containsKey("realRefundAmount") && request.get("realRefundAmount") != null) {
            String realRefundAmount = request.get("realRefundAmount").toString();
            reqData.put("realRefundAmount", realRefundAmount);
        }
        //szltFlag
        if (request.containsKey("szltFlag") && request.get("szltFlag") != null) {
            String szltFlag = request.get("szltFlag").toString();
            reqData.put("szltFlag", szltFlag);
        }
        //recFeeAmt
        if (request.containsKey("recFeeAmt") && request.get("recFeeAmt") != null) {
            String recFeeAmt = request.get("recFeeAmt").toString();
            reqData.put("recFeeAmt", recFeeAmt);
        }
        //szltRecfeeAmt
        if (request.containsKey("szltRecfeeAmt") && request.get("szltRecfeeAmt") != null) {
            String szltRecfeeAmt = request.get("szltRecfeeAmt").toString();
            reqData.put("szltRecfeeAmt", szltRecfeeAmt);
        }

        String savedPayType = null;

        //extend
        if (request.containsKey("extend") && request.get("extend") != null) {
            String extend = request.get("extend").toString();
            reqData.put("extend", extend);
            if (StringUtils.isNotBlank(extend)) {
                savedPayType = extend;
            }
        }

        //reqData.put("extend",extend);

//        reqData.put("sxfUuid",sxfUuid);
//        reqData.put("payWay",payWay);
//        reqData.put("payTime",payTime);
//        reqData.put("uuid",uuid);
//        reqData.put("mno",mno);
//        reqData.put("ordNo",ordNo);
//        reqData.put("amt",amt);
//        reqData.put("buyerId",buyerId);
//        reqData.put("transactionId",transactionId);
//        reqData.put("drType",drType);
//        reqData.put("payType",payType);
//        reqData.put("payBank",payBank);
//        reqData.put("pointAmount",pointAmount);
//        reqData.put("totalOffstAmt",totalOffstAmt);
//        reqData.put("settleAmt",settleAmt);
//        reqData.put("timeStamp",timeStamp);
//        reqData.put("bizCode",bizCode);
//        reqData.put("bizMsg",bizMsg);
//        reqData.put("openid",openid);
//        reqData.put("channelId",channelId);
//        reqData.put("subMechId",subMechId);
//        reqData.put("finishTime",finishTime);
//        reqData.put("clearDt",clearDt);
//        reqData.put("settlementBatchNo",settlementBatchNo);

        //reqData.put("realRefundAmount",realRefundAmount);
        //reqData.put("recFeeAmt",recFeeAmt);
        //reqData.put("recFeeRate",recFeeRate);
        //reqData.put("buyerAccount",buyerAccount);
        //reqData.put("origOrdNo",origOrdNo);
        //reqData.put("origUuid",origUuid);
        //reqData.put("scene",scene);
        //reqData.put("refBuyerAmt",refBuyerAmt);
        //reqData.put("extend",extend);


        Gson gson = new Gson();

        logger.info("/sxfPayCallbackV2" + "-" + ordNo + "--待验签数据:" + gson.toJson(reqData));

        //验签
        HashMap<String, Object> result = JSON.parseObject(gson.toJson(reqData),
                LinkedHashMap.class,
                Feature.OrderedField
        );

        String resultStr = RSASignature.getOrderContent(result);
//            if(!RSASignature.doCheck(resultStr, sign, SXFPaySign.sxfPublic)){
//                throw new Exception("验签失败");
//            }

        String successReturnValue = sxfPayOrderCallback(payTime, ordNo, amt, transactionId, settleAmt, payType, savedPayType);
        if (successReturnValue != null) return successReturnValue;
//        resultJson.put("code","success");
//        resultJson.put("msg","成功");
        logger.info("/sxfPayCallbackV2-ordNo" + ordNo + "--随行付回调成功");
        return SxfCallbackServiceImpl.SUCCESS_RETURN_VALUE;
    }

    public String sxfPayOrderCallback(String payTime, String ordNo, String amt, String transactionId, String settleAmt, String payType, String savedPayType) {
        try {

            logger.info("/sxfPayCallbackV2" + "-" + ordNo + "--验签成功");
            if (StringUtils.isBlank(ordNo)) {
                log.info("订单号为空");
                return SxfCallbackServiceImpl.SUCCESS_RETURN_VALUE;
            }
            if (ordNo.length()>20) {
                // POS机第三方订单号不一样需要再次查
                TradePaymentRecordsDO records=tradePaymentRecordsService.selectOneOrdNo(ordNo);
                if (records == null) {
                    logger.info("POS订单不存在| ordNo=" + ordNo);
                    return SxfCallbackServiceImpl.SUCCESS_RETURN_VALUE;
                }
                ordNo = records.getOrderSn();
            }

            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);

            if (payOrderInfo == null) {
//                throw new Exception("订单不存在");
                logger.info("订单不存在| ordNo=" + ordNo);
                return SxfCallbackServiceImpl.SUCCESS_RETURN_VALUE;
            }
            if (!"0".equals(payOrderInfo.getStatus())) {
                logger.info("订单已支付 | ordNo=" + ordNo + "| getStatus=" + payOrderInfo.getStatus());
                return SxfCallbackServiceImpl.SUCCESS_RETURN_VALUE;
            }


            payOrderInfo.setStatus("1");
            if (payType.equals("WECHAT")) {   //WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
                payOrderInfo.setPayType("wx");
                payOrderInfo.setWxAmt(Double.valueOf(amt));
            } else if (payType.equals("ALIPAY")) {
                payOrderInfo.setPayType("zfb");
                payOrderInfo.setZfbAmt(Double.valueOf(amt));
            } else if (payType.equals("UNIONPAY")) {
                payOrderInfo.setPayType("yl");
            }

            if (StringUtils.isNotBlank(savedPayType)) {
                payOrderInfo.setPayType(savedPayType);
            }


            payOrderInfo.setDzkAmt(Double.valueOf("0"));
            payOrderInfo.setPayDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTime).getTime()));    //支付时间
            payOrderInfo.setReceivedAmt(Double.valueOf(settleAmt));          //settleAmt商家入账金额
            payOrderInfo.setTransactionId(transactionId);

            BigDecimal orderAmt = BigDecimal.valueOf(payOrderInfo.getAmt());
            payOrderInfo.setActualAmt(orderAmt);
            Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
            if (StringUtils.equals("0",payOrderInfo.getChannelFeePayer())) {
                // 司机承担渠道费
                if (station != null && station.getIsShowSaasAmtCommission() == 0) {
                    // 后台订单列表不展示渠道费
                    BigDecimal recAmt = payOrderInfo.getReceivableAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrderInfo.getReceivableAmt());
                    BigDecimal disAmt = payOrderInfo.getDiscountAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrderInfo.getDiscountAmt());
                    BigDecimal couAmt = payOrderInfo.getDiscountCouponAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrderInfo.getDiscountCouponAmt());
                    BigDecimal amt1 = recAmt.subtract(disAmt).subtract(couAmt);
                    if (amt1.compareTo(BigDecimal.ZERO)<=0) {
                        amt1 = DecimalConstant.O_01;
                    }
                    payOrderInfo.setAmt(amt1.doubleValue());
                }
            }

            //修改订单状态
            int count = payOrderService.getUpdatePayOrder(payOrderInfo);


            if (count != 1) {
//                throw new Exception("订单修改失败");
                logger.info("订单修改失败| ordNo=" + ordNo.toString());
                return SxfCallbackServiceImpl.FAIL_RETURN_VALUE;
            }

            logger.info("/sxfPayCallbackV2-ordNo" + ordNo + "--更新订单成功");
//            这里是发放优惠券
            consumptionCouponIssuance(ordNo, 0.0);

            //打印飞鹅订单
            gzhNewsTemplateService.feiePush(payOrderInfo);
            gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);
            AppUserInfo appUserInfo = appUserInfoService.getById(payOrderInfo.getConsumerId());
            int integral = 0;
            try {
                integral = this.handleCallBack(payOrderInfo, appUserInfo);
            } catch (EndingException e) {
                logger.error("error========"+e);
            }
            // 微信模板通知-支付成功（加油成功）通知
            if (appUserInfo != null && StringUtils.isNotBlank(appUserInfo.getBlogOpenid()) ) {
                Map<String, String> templateParams = new HashMap<>();
                templateParams.put("openid", appUserInfo.getBlogOpenid());
                templateParams.put("stationName", payOrderInfo.getStationName());
                templateParams.put("oilName", payOrderInfo.getOilName());
                //获取用户电子会员卡信息
                BigDecimal dzkBalance = BigDecimal.ZERO;
                if (!MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone()) && ObjectUtils.isNotEmpty(payOrderInfo.getCardType())) {
                    CustomerElectronicCard cardInfo = electronicMembershipCardService.getCustomerElectronicCard(appUserInfo, payOrderInfo.getCardType(), station);
                    if (cardInfo != null) {
                        dzkBalance = cardInfo.getTotalAmt();
                    }

                 /*   customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(ordNo,
                            payOrderInfo.getCustomerPhone(),new BigDecimal(amt),payOrderInfo.getEnterpriseId().longValue(),
                            payOrderInfo.getStationId().longValue(),payType,null,payOrderInfo.getOilId(),PresentAmountRecord.businessName_payOrder,PresentAmountRecord.purpose_add);
*/
                }
                templateParams.put("payDetail", "实付" + payOrderInfo.getAmt() + "元，积分+" + integral);
                templateParams.put("walletBalance", dzkBalance.toString() + "元");
                logger.info("微信支付-微信模板参数：{}", templateParams);
                wxPushUtil.sendTemplateMsg(payOrderInfo.getEnterpriseId(), templateParams, WxTemplateEnum.REFUEL_SUCCESS);
            }

        } catch (Exception e) {
            logger.error("/sxfPayCallbackV2-ordNo" + ordNo + "订单更新失败", e);
            return SxfCallbackServiceImpl.FAIL_RETURN_VALUE;
        }
        return null;
    }

    // 金控接受异步异步通知
    @RequestMapping(value = "/JKNotice", consumes = "application/json", method = RequestMethod.POST)
    public void JKNotice(HttpServletRequest request, HttpServletResponse response) {
        // 接受异步消息
        try {
            String data = JKPayUtil.getParamByStream(request);
            JSONObject obj = JSON.parseObject(data);
            obj.put("orderInfo", obj.getString("orderInfo").replaceAll(" ", "+"));
            obj.put("signValue", obj.getString("signValue").replaceAll(" ", "+"));
            logger.info("金控开始回调参数" + obj);
            String signType = (String) obj.getString("signType");

            String signvalue = obj.getString("signValue");
            obj.remove("signValue");
            Map verifyMap = (Map) JSONObject.parse(obj.toString());
            String verifyContent = ParaUtils.createLinkString(ParaUtils.paraFilter(verifyMap));
            boolean checkverify = CfcaCertUtil.verifyValue(verifyContent, signvalue, public_certPath);
            if (checkverify) { //验签成功
                String orderInfo = Base64Util.decodeString(obj.get("orderInfo") + "");
                JSONObject orderInfoMessage = JSON.parseObject(orderInfo);
                logger.info(orderInfo);
                if (!"02".equals(orderInfoMessage.get("orderStatus") + "")) {
                    logger.info("金控订单状态不对:" + orderInfoMessage);
                    response.getWriter().print("000000");
                    throw new Exception("金控订单状态不对：" + orderInfoMessage);
                }
                //通过金控订单号，定位订单
                PayOrder payOrderInfo = payOrderMapper.selectOrderInfoByMerchantsNumber(orderInfoMessage.get("mfhcdOrderNo") + "");
                if (payOrderInfo == null) {
                    logger.info("金控订单跟新回调信息更新订单失败，当前订单未查询到" + orderInfoMessage);
                    throw new Exception("订单不存在");
                }
                if (!"0".equals(payOrderInfo.getStatus())) {
                    logger.info("getStatus" + payOrderInfo.getStatus());
                    if ("1".equals(payOrderInfo.getStatus())) {
                        response.getWriter().print("000000");
                        logger.info("金控订单跟新回调信息更新订单失败，当前订单已经更新过" + orderInfoMessage);
                    }
                    throw new Exception("金控订单状态不对" + orderInfoMessage);
                }
                payOrderInfo.setStatus("1");
                payOrderInfo.setDzkAmt(Double.valueOf("0"));
                payOrderInfo.setPayDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(orderInfoMessage.get("transFinishTime") + "").getTime()));    //支付时间
                payOrderInfo.setReceivedAmt(new BigDecimal(orderInfoMessage.get("tranAmt") + "").divide(new BigDecimal("100")).doubleValue());          //settleAmt商家入账金额
                payOrderInfo.setTransactionId(orderInfoMessage.get("cisOrderNo") + "");
                //修改订单状态
                int count = payOrderService.getUpdatePayOrder(payOrderInfo);

                if (count != 1) {
                    throw new Exception("订单修改失败");
                }
                response.getWriter().print("000000");
                try {
                    this.handleCallBack(payOrderInfo);
                } catch (Exception e) {
                    logger.info("error=======" + e);
                }
                //打印飞鹅订单
                gzhNewsTemplateService.feiePush(payOrderInfo);
                gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);

                //消费返额
              /*  customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(payOrderInfo.getOrderNo(),
                        payOrderInfo.getCustomerPhone(),new BigDecimal(payOrderInfo.getAmt()),payOrderInfo.getEnterpriseId().longValue(),
                        payOrderInfo.getStationId().longValue(),payOrderInfo.getPayType(),null,payOrderInfo.getOilId(),PresentAmountRecord.businessName_payOrder,PresentAmountRecord.purpose_add);
*/

            }
        } catch (Exception e) {
            logger.info("金控回调错误日志+" + e.getMessage());
            e.printStackTrace();
        }

    }

    public int handleCallBack(PayOrder payOrderInfo) throws EndingException {
/*        AppUserInfo queryAppUserInfo = new AppUserInfo();
        queryAppUserInfo.setStationId(payOrderInfo.getEnterpriseId()); // 兄弟，注意一点这里。之前人家这样写的，我也很无奈。
        queryAppUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());*/
        AppUserInfo appUserInfo = appUserInfoService.getById(payOrderInfo.getConsumerId());
        return handleCallBack(payOrderInfo, appUserInfo);
    }

    //    @Transactional
    public int handleCallBack(PayOrder payOrderInfo, AppUserInfo appUserInfo) throws EndingException {
        int integral = 0;
        if (appUserInfo == null) {
            return integral;
        }
        if (MobilePhoneUtil.isFakePhone(payOrderInfo.getCustomerPhone())) {
            return integral;
        }
        if (StringUtils.isBlank(appUserInfo.getNickName())) {
            appUserInfo.setNickName(appUserInfo.getBlogNickName());
        }

        integral = this.handleIntegralAndGrowUpValue(payOrderInfo, appUserInfo);
        this.handleCoupon(payOrderInfo, appUserInfo);


        return integral;
    }

    //    @Transactional
    public int handleIntegralAndGrowUpValue(PayOrder payOrderInfo, AppUserInfo userInfo) throws EndingException {
        int resultIntegral = 0;
        try {
            //油企
            logger.info("+handleIntegralAndGrowUpValue" + "-orderNo" + payOrderInfo.getOrderNo() + "--积分处理逻辑");
            // 更新后的订单

            CalculateIntegral calculateIntegral = new CalculateIntegral();
            calculateIntegral.setEnterpriseId(payOrderInfo.getEnterpriseId());
            calculateIntegral.setOilId(payOrderInfo.getOilId());
            calculateIntegral.setAmt(new BigDecimal(payOrderInfo.getAmt().toString()));
            calculateIntegral.setReceivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt()));
            calculateIntegral.setOilLiters(new BigDecimal(payOrderInfo.getOrderLiters()));
            calculateIntegral.setUserId(payOrderInfo.getConsumerId());      //此参数用作计算超级会员的积分

            CalculateIntegral calIntegral = this.calUserIntegral(calculateIntegral);
            payOrderService.updateGrowthValueByOrdNo(calIntegral.getGrowValue().longValue(),payOrderInfo.getOrderNo());
            if (StringUtils.equals("dzk", payOrderInfo.getPayType())) {
                // 如果是电子卡支付，积分变成配置的倍数
                Enterprise enterprise = enterpriseService.selectEnterpriseInfo(payOrderInfo.getEnterpriseId());
                if (enterprise != null && StringUtils.equals("1", enterprise.getCardFlag())) {
                    List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeMinAmt(CustomerCardSetting.builder()
                            .stationId(payOrderInfo.getEnterpriseId())
                            .delFlag("0").build());
                    if (cardRechargeSettingList.size() > 0) {
                        CustomerCardSetting setting = cardRechargeSettingList.get(0);
                        String multiple = setting.getEnjoyIntegralMultiple();
                        if (StringUtils.isNumeric(multiple)) {
                            int m = Integer.parseInt(multiple);
                            if (m > 1) calIntegral.setIntegral(calIntegral.getIntegral() * m);
                        }
                    }
                }
            }

            if (StringUtils.isBlank(payOrderInfo.getCustomerPhone())) {
                throw new EndingException("手机号不存在");
            }


            if (userInfo == null) {
                throw new EndingException("查无此用户");
            }

            logger.info("+handleIntegralAndGrowUpValue"
                    + "-" + payOrderInfo.getOrderNo()
                    + "--原有积分：" + userInfo.getIntegral() + ";原有成长值：" + userInfo.getGrowUpValue());

            Integer integral = userInfo.getIntegral();
            Integer growUpValue = userInfo.getGrowUpValue();
            logger.info("+handleIntegralAndGrowUpValue"
                    + "-" + payOrderInfo.getOrderNo()
                    + "--增加积分：" + calIntegral.getIntegral() + ";增加成长值：" + calIntegral.getGrowValue());

            boolean intGreaterO = calIntegral.getIntegral() > 0;
            boolean growGreaterO = calIntegral.getGrowValue() > 0;

            AppUserInfo updateAppUserInfo = new AppUserInfo();
            updateAppUserInfo.setStationId(payOrderInfo.getEnterpriseId());
            updateAppUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
            if (intGreaterO) {
                updateAppUserInfo.setIntegral(calIntegral.getIntegral() + integral);
            }
            if (growGreaterO) {
                updateAppUserInfo.setGrowUpValue(calIntegral.getGrowValue() + growUpValue);
            }
            if (intGreaterO || growGreaterO) {
                appUserInfoService.updateAppUserIntegral(updateAppUserInfo);
            }

            if (intGreaterO || calculateIntegral.getCashIntegral() > 0) {
                CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                customerPointsRecord.setCreateTime(new Date());
                customerPointsRecord.setOrderNo(payOrderInfo.getOrderNo());
                customerPointsRecord.setRecordType("+");
                customerPointsRecord.setMobilePhone(payOrderInfo.getCustomerPhone());
                customerPointsRecord.setStationId(payOrderInfo.getStationId()); //油站
                customerPointsRecord.setCustomerName(userInfo.getNickName());
                customerPointsRecord.setAction(integralTypeEnum.REFUEL);
                customerPointsRecord.setIntegral(calculateIntegral.getIntegral());
                customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);
                customerPointsRecordService.sendwxgzh(payOrderInfo.getStationId(), payOrderInfo.getCustomerPhone(), customerPointsRecord.getIntegral(), updateAppUserInfo.getIntegral(), "+");
            }

            // 推送
            resultIntegral = calIntegral.getIntegral();
            userInfo.setIntegral(userInfo.getIntegral() + calIntegral.getIntegral());
            userInfo.setGrowUpValue(userInfo.getGrowUpValue() + calIntegral.getGrowValue());
            gzhNewsTemplateService.pushConsumeToUser(userInfo, payOrderInfo, calIntegral.getIntegral());
            // gzhNewsTemplateService.feiePush(payOrderInfo);
        } catch (EndingException e) {
            logger.error("+handleIntegralAndGrowUpValue-orderNo:" + payOrderInfo.getOrderNo() + "，积分添加失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new EndingException("+handleIntegralAndGrowUpValue-orderNo:" + payOrderInfo.getOrderNo() + "，积分添加失败" + e);
        } catch (Exception e) {
            logger.error("+handleIntegralAndGrowUpValue-orderNo" + payOrderInfo.getOrderNo() + "，积分添加失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new EndingException("+handleIntegralAndGrowUpValue-orderNo:" + payOrderInfo.getOrderNo() + "，积分添加失败" + e);
        }

        logger.info("+handleIntegralAndGrowUpValue" + "-" + payOrderInfo.getOrderNo() + "--积分处理完毕");
        return resultIntegral;
    }


    @Transactional
    public Boolean handleCoupon(PayOrder payOrder, AppUserInfo userInfo) throws EndingException {
        logger.info("+handleCoupon" + "-orderNo" + payOrder.getOrderNo() + "--开始处理处理优惠券");

        try {
            Station station = enterpriseService.selectStationById(payOrder.getStationId());

            if (station.getEnterprise().getCouponEnabledFlag() == null || !"1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                logger.info("+handleCoupon" + "-orderNo" + payOrder.getOrderNo() + "--未开启优惠券");
                return null;
            }

            // --
            int i = couponService.initiativeCoupon(userInfo,
                    station.getStationId(),
                    new BigDecimal(payOrder.getReceivableAmt().toString()),payOrder.getOrderNo()
            );

            if (i > 0) {
                couponService.pushWxGzhInitiativeCouponInfo(station, payOrder, i, userInfo);
            }
            // --

            if (StringUtils.isBlank(payOrder.getDiscountCoupon())) {
                logger.info("+handleCoupon" + "-orderNo" + payOrder.getOrderNo() + "--未使用优惠劵");
                return null;
            }

            logger.info("+handleCoupon" + "-orderNo" + payOrder.getOrderNo() + "--优惠劵id:" + payOrder.getDiscountCoupon());

            // 验证有木有核销的劵
            Map<String, Object> param = new HashMap<>();
            param.put("couponUserId", payOrder.getDiscountCoupon());
            List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
            if (couponUserList == null || couponUserList.size() != 1) {
                throw new EndingException("要核销的优惠券数量不对");
            }

            // 核销优惠券
            couponService.updateCouponUser(CouponUser
                    .builder()
                    .verificationTime(new Date())
                    .couponUserId(Integer.valueOf(payOrder.getDiscountCoupon()))
                    .couponIsUsed("1")
                    .build()
            );

            CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate
                    .builder()
                    .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                    .build()
            );

            if (ct == null) {
                return null;
            }

            // 更新优惠劵模板，加上使用量
            couponService.updateCouponTemplate(CouponTemplate
                    .builder()
                    .useCouponNum(ct.getUseCouponNum() + 1)
                    .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                    .build()
            );

        } catch (EndingException e) {
            logger.error("+handleCoupon-orderNo:" + payOrder.getOrderNo() + "，优惠券处理失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new EndingException("+handleCoupon-orderNo:" + payOrder.getOrderNo() + "，优惠券处理失败" + e);
        } catch (Exception e) {
            logger.error("+handleCoupon-orderNo" + payOrder.getOrderNo() + "，优惠劵处理失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new EndingException("+handleCoupon-orderNo:" + payOrder.getOrderNo() + "，优惠券处理失败" + e);
        }

        logger.info("+handleCoupon" + "-orderNo" + payOrder.getOrderNo() + "--结束处理处理优惠券");
        return null;
    }

    //电子卡支付
    @Transactional
    @RequestMapping(value = "/dzkPaySetV2", method = RequestMethod.GET)
    @ApiOperation(value = "电子卡支付", httpMethod = "GET", notes = "电子卡支付")
    public String dzkPaySet(@RequestParam String ordNo, String couponUserId) {
        Gson gson = new Gson();
        ResultData resultData = null;

        try {
            logger.info("/dzkPaySetV2-" + ordNo + "--ordNo:" + ordNo);
            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (payOrderInfo == null) {
                throw new EndingException("无此订单");
            }
            if (!payOrderInfo.getStatus().equals("0")) {
                throw new EndingException("此笔订单状态不对");
            }

            Integer stationId = payOrderInfo.getStationId();
            String oilName = payOrderInfo.getOilName();      //油品名字
            String cardType = payOrderInfo.getCardType();   //该订单对应的油品类型
            String amt = payOrderInfo.getAmt().toString();  //订单支付金额
            String receivableAmt = payOrderInfo.getReceivableAmt().toString();
            //获取油站信息
            Station stationInfo = enterpriseService.selectStationById(stationId);

            AppUserInfo appUserInfo = appUserInfoService.getById(payOrderInfo.getConsumerId());

            if (appUserInfo == null || StringUtils.isBlank(appUserInfo.getMobilePhone())) {
                throw new EndingException("用户不存在");
            }
            Boolean couponflag = false;
            BigDecimal couponAmt = BigDecimal.ZERO;
            if (StringUtils.isNotBlank(couponUserId)) {
                logger.info("/dzkPaySetV2-使用优惠券id:" + couponUserId);
                //计算使用优惠券后传参优惠券ID
                payOrderInfo.setDiscountCoupon(couponUserId);
                //计算优惠券
                CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrderInfo, stationInfo);
                logger.info("/dzkPaySetV2-优惠券信息：" + couponUser);
                if (couponUser != null) {
                    couponflag = true;
                    couponAmt = couponUser.getCouponAmtByCNY();
                    PayOrder p = new PayOrder();                            //更新订单参数
                    //使用优惠券时要更新的订单信息
                    amt = couponUser.getNewAmtByCoupon().toString();
                    payOrderInfo.setDiscountCoupon(couponUserId);
                    payOrderInfo.setDiscountCouponAmt(couponUser.getCouponAmtByCNY().doubleValue());
                    payOrderInfo.setAmt(Double.valueOf(amt));
                    payOrderInfo.setOrderNo(ordNo);
//                    payOrderService.getUpdatePayOrder(p);
                    logger.info("/dzkPaySetV2-电子卡实付金额：" + amt);
                }
            }

            BigDecimal balance = BigDecimal.ZERO;                                                  //电子会员卡余额
            Integer enterpriseId = stationInfo.getEnterpriseId();
            //获取用户电子会员卡信息

            CustomerElectronicCard cardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(appUserInfo, cardType, stationInfo);

            balance = cardInfo.getTotalAmt();
//
//            if(balance == null || new BigDecimal(amt).compareTo(balance) == 1){
//                throw new EndingException("电子卡余额不足");
//            }
            //判断是否有冻结的充值活动导致不够余额支付
            BigDecimal orderAmt = new BigDecimal(amt);
            ElectronicCardSubRes res = cardInfo.subtractAmount(orderAmt);
            if (!res.isSuccess()) {
                throw new EndingException("电子卡余额不足");
            }

            electronicMembershipCardService.isNonpayment(payOrderInfo.getCustomerPhone(), stationInfo, orderAmt, balance);

            //本次消费后的余额
            BigDecimal newBalance = cardInfo.getTotalAmt();


            //更新电子会员卡余额
            electronicMembershipCardService.updateElectronicCardInfoByPhone(CustomerElectronicCard.builder()
                            .amt(cardInfo.getAmt())
                            .mobilePhone(appUserInfo.getMobilePhone())
                            .cardOilsType(cardType)
                            .recentlyTime(new Date())
                            .presentAmt(cardInfo.getPresentAmt()),
                    stationInfo);
            //更新立减活动的优惠余额
            reductionActivityBalanceRecordService.updateBalance(cardType, appUserInfo.getUserId().longValue(), stationId.longValue(), enterpriseId.longValue(), payOrderInfo.getRechargeDiscountAmt(), orderAmt, appUserInfo.getMobilePhone());
            if (res.getPresentAmt().compareTo(BigDecimal.ZERO) > 0) {

            }
            //生成消费记录
            electronicMembershipCardService.insetCardUseRecordConsumption(CustomerCardUseRecord.builder()
                    .orderNo(ordNo)
                    .customerNo(appUserInfo.getMemberCode())
                    .amt(res.getAmt())
                    .presentAmt(res.getPresentAmt())
                    .status("1")
                    .mobilePhone(cardInfo.getMobilePhone())
                    .cardOilsType(cardInfo.getCardOilsType())
                    .balance(newBalance)
                    .stationId(stationId)
                    .enterpriseId(enterpriseId)
                    .usageType("-")
                    .createTime(new Date())
                    .build()
            );
            if(res.getPresentAmt().compareTo(BigDecimal.ZERO)>0){
                presentAmountRecordService.createRecord(res.getPresentAmt(),PresentAmountRecord.businessName_payOrder,cardInfo.getMobilePhone(),ordNo,PresentAmountRecord.purpose_subtract,cardInfo.getId().longValue(),null);
            }


            BigDecimal discountAmt = BigDecimal.ZERO;
            if (couponflag) {
                discountAmt = new BigDecimal(receivableAmt).subtract(orderAmt.subtract(couponAmt)); //电子卡优惠金额
            } else {
                discountAmt = new BigDecimal(receivableAmt).subtract(orderAmt); //电子卡优惠金额
            }


            payOrderInfo.setStatus("1");
            payOrderInfo.setPayType("dzk");
            payOrderInfo.setPayDate(new Timestamp(new Date().getTime()));
            // 优化  当前订单赋值错误 ，应该是应收金额，不是实收金额
//            payOrderInfo.setReceivableAmt(Double.valueOf(amt));
            payOrderInfo.setReceivedAmt(Double.valueOf(amt));
            payOrderInfo.setDiscountAmt(Double.valueOf(discountAmt.toString()));
            payOrderInfo.setAmt(Double.valueOf(amt));
            payOrderInfo.setWxAmt(Double.valueOf("0"));
            payOrderInfo.setZfbAmt(Double.valueOf("0"));
            payOrderInfo.setDzkAmt(Double.valueOf(amt));
            payOrderInfo.setBalance(newBalance);
            payOrderInfo.setActualRechargeAmt(res.getAmt());


            //更新订单信息

            payOrderService.getUpdatePayOrder(payOrderInfo);


            //消费返额
            CalPresentAmt calPresentAmt = customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(payOrderInfo.getOrderNo(),
                    payOrderInfo.getCustomerPhone(), BigDecimal.valueOf(payOrderInfo.getReceivableAmt()), BigDecimal.valueOf(payOrderInfo.getAmt()), payOrderInfo.getEnterpriseId().longValue(),
                    payOrderInfo.getStationId().longValue(), "dzk_wx", cardInfo.getCardOilsType(), payOrderInfo.getOilGun(), payOrderInfo.getOilId(), PresentAmountRecord.businessName_payOrder, PresentAmountRecord.purpose_add);
            if (calPresentAmt.getPresentAmt().compareTo(BigDecimal.ZERO) > 0) {
                electronicMembershipCardService.insetCardUseRecordConsumption(CustomerCardUseRecord.builder()
                        .orderNo(ordNo + "1")
                        .customerNo(appUserInfo.getMemberCode())
                        .presentAmt(calPresentAmt.getPresentAmt())
                        .status("1")
                        .mobilePhone(cardInfo.getMobilePhone())
                        .cardOilsType(cardInfo.getCardOilsType())
                        .balance(newBalance.add(calPresentAmt.getPresentAmt()))
                        .stationId(stationId)
                        .enterpriseId(enterpriseId)
                        .usageType("+")
                        .createTime(new Date())
                        .payType("cs_pt")
                        .build()
                );
            }


            //飞鹅打印机  打印订单
            gzhNewsTemplateService.feiePush(payOrderInfo);
            gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);
            try {
                this.handleCallBack(payOrderInfo, appUserInfo);
            } catch (EndingException e) {
                logger.error("==========error==========", e);
            }

            return ResultData.successJson("支付成功");

        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/dzkPaySetV2-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }

    }
    @Async
    @RequestMapping(value = "/consumptionCouponIssuance", method = RequestMethod.GET)
    @ApiOperation(value = "消费后发券", httpMethod = "GET", notes = "消费后发券retCode为0则成功，为其他的则不跳转，非空判断返回值为空也不跳转")
    public String consumptionCouponIssuance(@RequestParam String ordNo, Double amt) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String jsonMsg = gson.toJson(ResultData.error(new CodeMsg(500, "初始化返回值")));
        try {
            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
            String activeId = couponService.checkCouponActivity(payOrderInfo.getEnterpriseId(), payOrderInfo, amt);


            if (!StringUtils.isEmpty(activeId)) {
                DrawCoupon drawCoupon = new DrawCoupon();
                drawCoupon.setMobilePhone(payOrderInfo.getCustomerPhone());
                drawCoupon.setCouponIssueId(activeId);
                drawCoupon.setOrdNo(payOrderInfo.getOrderNo());
                drawCoupon.setCouTemIds("1000");
                drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
                jsonMsg = couponController.drawCouponsCopy(drawCoupon);

                ResultData dat = gson.fromJson(jsonMsg, ResultData.class);
                logger.info("消费后发券消息通知-----参数打印jsonMsg：" + jsonMsg);
                // 微信模板通知-优惠券发放通知
                if (StringUtils.isNotEmpty(payOrderInfo.getMobilePhone()) && (payOrderInfo.getPayType().equals("wx") || payOrderInfo.getPayType().equals("dzk"))
                        && dat.getRetCode() == 0 && dat.getData() != null) {
                    AppUserInfo queryAppUserInfo = new AppUserInfo();     //查询客户信息传递参数
                    queryAppUserInfo.setStationId(payOrderInfo.getEnterpriseId());
                    queryAppUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                    AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(queryAppUserInfo);
                    Map<String, String> templateParams = new HashMap<>();
                    templateParams.put("openid", appUserInfo.getBlogOpenid());
                    templateParams.put("stationName", payOrderInfo.getStationName());
//                    List<CouponTemplate> drawTemList=(List<CouponTemplate>) dat.getData();
//                    if(drawTemList.size()==0) {
//                    	logger.info("消费后发券消息通知-微信模板参数,无数据不推送");
//                    	return jsonMsg;
//                    }
//                    Map<String, Long> couponTypeCountMap = drawTemList.stream()
//                            .collect(Collectors.groupingBy(CouponTemplate::getCouponType, Collectors.counting()));
//
//                    Long number=couponTypeCountMap.get(drawTemList.get(0).getCouponType());
//                    String str=CouponTemplateCouponEnum.getKey(Integer.valueOf(drawTemList.get(0).getCouponType()));
//                    templateParams.put("couponContent", "恭喜获得"+str+number+"张");
//                    logger.info("消费后发券消息通知-微信模板参数：{}", templateParams);
//                    wxPushUtil.sendTemplateMsg(payOrderInfo.getEnterpriseId(), templateParams, WxTemplateEnum.COUPON_DISTRIBUTION);
                    List<Map<String, Object>> drawTemList = (List<Map<String, Object>>) dat.getData();
                    Map<String, Long> couponTypeCountMap = new HashMap<String, Long>();
                    for (Map<String, Object> ma : drawTemList) {
                        long typeLong = couponTypeCountMap.get(ma.get("couponType").toString() + "_couponType") == null ? 0 : couponTypeCountMap.get(ma.get("couponType").toString() + "_couponType");
                        typeLong++;
                        couponTypeCountMap.put(ma.get("couponType").toString() + "_couponType", typeLong);
                    }
                    String strSl = couponTypeCountMap.size() > 1 ? "......" : "";
                    Long number = couponTypeCountMap.get(drawTemList.get(0).get("couponType") + "_couponType");
                    String str = CouponTemplateCouponEnum.getKey(Integer.valueOf(drawTemList.get(0).get("couponType").toString()));
                    templateParams.put("couponContent", "恭喜获得" + str + number + "张" + strSl);
                    System.out.println("消费后发券消息通知-微信模板参数：{}" + templateParams);
                    wxPushUtil.sendTemplateMsg(payOrderInfo.getEnterpriseId(), templateParams, WxTemplateEnum.COUPON_DISTRIBUTION);
                } else {
                    logger.info("消费后发券消息通知-微信模板参数----参数条件不够，不进行推送");
                }
            }
        } catch (Exception e) {
            // 处理子方法抛出的异常
            logger.info("消费后领券发生异常：" + e.getMessage());
            jsonMsg = gson.toJson(ResultData.error(new CodeMsg(500, e.getMessage())));

        }
        return jsonMsg;
    }

    //电子卡支付
    @Transactional
    @RequestMapping(value = "/newDzkCouponPaySetV3", method = RequestMethod.GET)
    @ApiOperation(value = "电子卡支付", httpMethod = "GET", notes = "电子卡支付")
    public ResultData newDzkCouponPaySetV3(@RequestParam String ordNo, String couponUserId,
                                           @RequestParam(required = false, defaultValue = "dzk_wx") String payType,
                                           @RequestParam(required = false, defaultValue = "false") boolean genericPay) {
        //Gson gson =new Gson();
        //ResultData resultData = null;

        try {
//            logger.info("/newDzkCouponPaySetV3-" + ordNo + "--ordNo:" + ordNo);
            logger.info("/newDzkCouponPaySetV3---,ordNo:[{}],couponUserId:[{}],payType:[{}],genericPay:[{}]",ordNo,couponUserId,payType,genericPay);
            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (payOrderInfo == null) {
                throw new EndingException("无此订单");
            }
            if (!payOrderInfo.getStatus().equals("0")) {
                throw new EndingException("此笔订单状态不对");
            }

            Integer stationId = payOrderInfo.getStationId();
            //String oilName =payOrderInfo.getOilName();      //油品名字
            String cardType = payOrderInfo.getCardType();   //该订单对应的油品类型
            if (genericPay) {
                // 通用卡支付
                cardType = ElectronCardType.GENERIC.getKey();
            }
            String amt = payOrderInfo.getAmt().toString();  //订单支付金额
            //String receivableAmt = payOrderInfo.getReceivableAmt().toString();
            //获取油站信息
            Station stationInfo = enterpriseService.selectStationById(stationId);

            AppUserInfo appUserInfo = appUserInfoService.getById(payOrderInfo.getConsumerId());

            if (appUserInfo == null || StringUtils.isBlank(appUserInfo.getMobilePhone())) {
                throw new EndingException("用户不存在");
            }
            //  实例化折扣金额，做非空判断
            Double disamt = 0D;
            if (payOrderInfo.getDiscountAmt() != null) {
                disamt = payOrderInfo.getDiscountAmt();
            }


            logger.info("newDzkCouponPaySetV3---,修改优惠劵状态,couponUserId:[{}]",couponUserId);
            if (StringUtils.isNotBlank(couponUserId)) {
                logger.info("/dzkPaySetV2-使用优惠券id:" + couponUserId);


                //计算使用优惠券后传参优惠券ID
                payOrderInfo.setDiscountCoupon(couponUserId);
                //计算优惠券
                CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrderInfo, stationInfo);
                logger.info("/newDzkCouponPaySetV3-优惠券信息：" + couponUser);
                if (couponUser != null) {
                    payOrderInfo.setDiscountCoupon(couponUserId);
//                    payOrderInfo.setDiscountCouponAmt(payOrderInfo.getReceivableAmt()-disamt-payOrderInfo.getAmt());
//                    payOrderInfo.setOrderNo(ordNo);
                    // 核销优惠券
                    couponService.updateCouponUser(CouponUser
                            .builder()
                            .verificationTime(new Date())
                            .couponUserId(Integer.parseInt(couponUserId))
                            .couponIsUsed("1")
                            .build()
                    );
                }
            }

            BigDecimal balance = BigDecimal.ZERO;                                                  //电子会员卡余额
            Integer enterpriseId = stationInfo.getEnterpriseId();
            //获取用户电子会员卡信息

            CustomerElectronicCard cardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(appUserInfo, cardType, stationInfo);

            balance = cardInfo.getTotalAmt();
            BigDecimal orderAmt = new BigDecimal(amt);

            if(balance == null || balance.compareTo(orderAmt) < 0){
                throw new EndingException("卡余额不足");
            }

            //判断是否有冻结的充值活动导致不够余额支付
            electronicMembershipCardService.isNonpayment(payOrderInfo.getCustomerPhone(), stationInfo, orderAmt, balance);

            ElectronicCardSubRes res = cardInfo.subtractAmount(orderAmt);
            if (!res.isSuccess()) {
                throw new EndingException("卡余额不足");
            }


            //本次消费后的余额
            BigDecimal newBalance = cardInfo.getTotalAmt();

            //更新电子会员卡余额
            electronicMembershipCardService.updateElectronicCardInfoByPhone(CustomerElectronicCard.builder()
                            .amt(cardInfo.getAmt())
                            .presentAmt(cardInfo.getPresentAmt())
                            .mobilePhone(appUserInfo.getMobilePhone())
                            .cardOilsType(cardType)
                            .recentlyTime(new Date()),
                    stationInfo);

            //更新立减活动的优惠余额
            reductionActivityBalanceRecordService.updateBalance(cardType, appUserInfo.getUserId().longValue(), stationId.longValue(), enterpriseId.longValue(), payOrderInfo.getRechargeDiscountAmt(), orderAmt, appUserInfo.getMobilePhone());

            //生成消费记录
            electronicMembershipCardService.insetCardUseRecordConsumption(CustomerCardUseRecord.builder()
                    .orderNo(ordNo)
                    .customerNo(appUserInfo.getMemberCode())
                    .amt(res.getAmt())
                    .presentAmt(res.getPresentAmt())
                    .status("1")
                    .mobilePhone(cardInfo.getMobilePhone())
                    .cardOilsType(cardInfo.getCardOilsType())
                    .balance(newBalance)
                    .stationId(stationId)
                    .enterpriseId(enterpriseId)
                    .usageType("-")
                    .createTime(new Date())
                    .build()
            );
            if(res.getPresentAmt().compareTo(BigDecimal.ZERO)>0){
                presentAmountRecordService.createRecord(res.getPresentAmt(),PresentAmountRecord.businessName_payOrder,cardInfo.getMobilePhone(),ordNo,PresentAmountRecord.purpose_subtract,cardInfo.getId().longValue(),null);

            }


            //BigDecimal discountAmt = new BigDecimal(receivableAmt).subtract(new BigDecimal(amt)); //电子卡优惠金额
            payOrderInfo.setActivityId(null);
            payOrderInfo.setStatus("1");
            payOrderInfo.setPayType("dzk");
            payOrderInfo.setPayDate(new Timestamp(new Date().getTime()));

            //payOrderInfo.setDiscountAmt(Double.valueOf(discountAmt.toString()));
            payOrderInfo.setAmt(Double.valueOf(amt));
            payOrderInfo.setWxAmt(Double.valueOf("0"));
            payOrderInfo.setZfbAmt(Double.valueOf("0"));
            payOrderInfo.setDzkAmt(Double.valueOf(amt));
            payOrderInfo.setBalance(newBalance);
            payOrderInfo.setActualRechargeAmt(res.getAmt());


            //更新订单信息
            payOrderService.getUpdatePayOrder(payOrderInfo);


            //消费返额
            CalPresentAmt calPresentAmt = customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(payOrderInfo.getOrderNo(),
                    payOrderInfo.getCustomerPhone(), BigDecimal.valueOf(payOrderInfo.getReceivableAmt()), BigDecimal.valueOf(payOrderInfo.getAmt()), payOrderInfo.getEnterpriseId().longValue(),
                    payOrderInfo.getStationId().longValue(), payType, cardInfo.getCardOilsType(), payOrderInfo.getOilGun(), payOrderInfo.getOilId(), PresentAmountRecord.businessName_payOrder, PresentAmountRecord.purpose_add);
            if (calPresentAmt.getPresentAmt().compareTo(BigDecimal.ZERO) > 0) {
                electronicMembershipCardService.insetCardUseRecordConsumption(CustomerCardUseRecord.builder()
                        .orderNo(ordNo + "1")
                        .customerNo(appUserInfo.getMemberCode())
                        .presentAmt(calPresentAmt.getPresentAmt())
                        .status("1")
                        .mobilePhone(cardInfo.getMobilePhone())
                        .cardOilsType(cardInfo.getCardOilsType())
                        .balance(newBalance.add(calPresentAmt.getPresentAmt()))
                        .stationId(stationId)
                        .enterpriseId(enterpriseId)
                        .usageType("+")
                        .createTime(new Date())
                        .payType("cs_pt")
                        .build()
                );
            }


            int integral = this.handleCallBack(payOrderInfo, appUserInfo);
            payOrderInfo.setIntegral(String.valueOf(integral));
            payOrderInfo.setPresentAmt(calPresentAmt.getPresentAmt());
            //  飞鹅打印机  打印订单
            gzhNewsTemplateService.feiePush(payOrderInfo);
            gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);
            // 微信模板通知-支付成功（加油成功）通知
            Map<String, String> templateParams = new HashMap<>();
            templateParams.put("openid", appUserInfo.getBlogOpenid());
            templateParams.put("stationName", payOrderInfo.getStationName());
            templateParams.put("oilName", payOrderInfo.getOilName());
            templateParams.put("payDetail", "实付" + payOrderInfo.getAmt() + "元，积分+" + integral);
            templateParams.put("walletBalance", newBalance + "元");
            logger.info("电子卡支付-微信模板参数：{}", templateParams);
            wxPushUtil.sendTemplateMsg(payOrderInfo.getEnterpriseId(), templateParams, WxTemplateEnum.REFUEL_SUCCESS);
           consumptionCouponIssuance(payOrderInfo.getOrderNo(), payOrderInfo.getAmt());

            return ResultData.success("支付成功");
        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/dzkPaySetV2-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.error(e.getMessage());
        }

    }


    // 金控接受异步异步通知
    @RequestMapping(value = "/yunHuaNotice", consumes = "application/json", method = RequestMethod.POST)
    public void yunHuaNotice(HttpServletRequest request, HttpServletResponse response) {
        // 接受异步消息
        try {
            // 获取当前请求的域名
            String requestUrl = request.getRequestURI();


            String data = JKPayUtil.getParamByStream(request);
            JSONObject obj = JSON.parseObject(data);
            logger.info("云华开始回调" + obj);
            //做域名校验  判断
//            if(!"".equals(requestUrl)){
//                response.getWriter().print("000000");
//                logger.info("云华回调接口失败，请求地址错误");
//                return;
//            }

            String status = obj.getString("status");
            if ("3".equals(status)) { //显示支付成功

                BigDecimal amt = obj.getBigDecimal("txnAmt");
                String orderNo = obj.getString("clientSerialNo");
                String payTime = obj.getString("payTime");
                String transPayNo = obj.getString("transPayNo");
                String translnfoNo = obj.getString("transInfoNo");
                String payOrderNo = obj.getString("payOrderNo");
                String merchantDisAmt = obj.getString("merchantDisAmt");
                String sponsorDisAmt = obj.getString("sponsorDisAmt");
                String marketingDisAmt = obj.getString("marketingDisAmt");
                String platformDisAmt = obj.getString("platformDisAmt");
                String payAmt = obj.getString("payAmt");

                //通过金控订单号，定位订单
                PayOrder payOrderInfo = payOrderMapper.selectOrderInfoByOrdNo(orderNo + "");
                if (payOrderInfo == null) {
                    logger.info("云华订单跟新回调信息更新订单失败，当前订单未查询到" + obj);
                    throw new Exception("订单不存在");
                }

                payOrderInfo.setStatus("1");
                payOrderInfo.setDzkAmt(Double.valueOf("0"));
//                payOrderInfo.setPayDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTime).getTime()));    //支付时间
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                payOrderInfo.setPayDate(timestamp);
                payOrderInfo.setReceivedAmt(amt.doubleValue());          //settleAmt商家入账金额
                payOrderInfo.setTransactionId(transPayNo);
                payOrderInfo.setMerchantsNumber(translnfoNo);

                BigDecimal orderAmt = BigDecimal.valueOf(payOrderInfo.getAmt());
                payOrderInfo.setActualAmt(orderAmt);
                Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
                if (StringUtils.equals("0",payOrderInfo.getChannelFeePayer())) {
                    // 司机承担渠道费
                    if (station != null && station.getIsShowSaasAmtCommission() == 0) {
                        // 后台订单列表不展示渠道费
                        BigDecimal recAmt = payOrderInfo.getReceivableAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrderInfo.getReceivableAmt());
                        BigDecimal disAmt = payOrderInfo.getDiscountAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrderInfo.getDiscountAmt());
                        BigDecimal couAmt = payOrderInfo.getDiscountCouponAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(payOrderInfo.getDiscountCouponAmt());
                        BigDecimal amt1 = recAmt.subtract(disAmt).subtract(couAmt);
                        if (amt1.compareTo(BigDecimal.ZERO)<=0) {
                            amt1 = DecimalConstant.O_01;
                        }
                        payOrderInfo.setAmt(amt1.doubleValue());
                    }
                }

                //修改订单状态
                int count = payOrderService.getUpdatePayOrder(payOrderInfo);
              /*  customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(orderNo,
                        payOrderInfo.getCustomerPhone(),new BigDecimal(payOrderInfo.getAmt()),payOrderInfo.getEnterpriseId().longValue(),
                        payOrderInfo.getStationId().longValue(),payOrderInfo.getPayType(),null,payOrderInfo.getOilId(),PresentAmountRecord.businessName_payOrder,PresentAmountRecord.purpose_add);
*/


                if (count != 1) {
                    throw new Exception("订单修改失败");
                }
//                if (!StringUtils.equals("pos",payOrderInfo.getPayType())) {
//                    // 支付发券结果
//                    String consumptionReturn = consumptionCouponIssuance(orderNo);
//                    logger.info("云化支付发券结果", consumptionReturn);
//                    this.handleCallBack(payOrderInfo);
//                }

                if (!MobilePhoneUtil.isFakePhone(payOrderInfo.getCustomerPhone())) {
                    // 支付发券结果
                     consumptionCouponIssuance(orderNo, 0.0);
                    int integral = 0;
                    try {
                        integral = this.handleCallBack(payOrderInfo);
                    } catch (EndingException e) {
                        logger.info("error=======" + e);
                    }
                    //优惠卷核销

                    if (station != null) {
                        Integer enterpriseId = station.getEnterpriseId();   //油企ID
                        AppUserInfo appUserInfo = new AppUserInfo();
                        appUserInfo.setStationId(enterpriseId);
                        //appUserInfo.setUnionId(payOrderInfo.getUnionId());
                        appUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                        AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                        if (userInfo != null) {
                            //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                            if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                                //修改优惠券状态
                                if (StringUtils.isNotBlank(payOrderInfo.getDiscountCoupon())) {

                                    logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
                                    Map<String, Object> param = new HashMap<>();
                                    param.put("couponUserId", payOrderInfo.getDiscountCoupon());
                                    List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
                                    if (null != couponUserList && couponUserList.size() == 1) {
                                        couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
                                        CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(couponUserList.get(0).getCouponTemplateId()).build());
                                        if (null != ct) {
                                            couponService.updateCouponTemplate(CouponTemplate.builder()
                                                    .useCouponNum(ct.getUseCouponNum() + 1)
                                                    .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                                                    .build());
                                        }
                                    }
                                }
                                int i = couponService.initiativeCoupon(userInfo, station.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()),orderNo);
                                //优惠券主动领取后推送消息
                                if (i > 0)
                                    couponService.pushWxGzhInitiativeCouponInfo(station, payOrderInfo, i, appUserInfo);
                            }
                            if (StringUtils.isNotBlank(userInfo.getBlogOpenid())) {
                                Map<String, String> templateParams = new HashMap<>();
                                templateParams.put("openid", userInfo.getBlogOpenid());
                                templateParams.put("stationName", payOrderInfo.getStationName());
                                templateParams.put("oilName", payOrderInfo.getOilName());
                                //获取用户电子会员卡信息
                                BigDecimal dzkBalance = BigDecimal.ZERO;
                                if (!MobilePhoneUtil.isFakePhone(userInfo.getMobilePhone()) && ObjectUtils.isNotEmpty(payOrderInfo.getCardType())) {
                                    CustomerElectronicCard cardInfo = electronicMembershipCardService.getCustomerElectronicCard(userInfo, payOrderInfo.getCardType(), station);
                                    if (cardInfo != null) {
                                        dzkBalance = cardInfo.getTotalAmt();
                                    }
                                }
                                templateParams.put("payDetail", "实付" + payOrderInfo.getAmt() + "元，积分+" + integral);
                                templateParams.put("walletBalance", dzkBalance.toString() + "元");
                                logger.info("微信支付-微信模板参数：{}", templateParams);
                                wxPushUtil.sendTemplateMsg(payOrderInfo.getEnterpriseId(), templateParams, WxTemplateEnum.REFUEL_SUCCESS);
                            }
                        }
                    }
                }


                response.getWriter().print("{\"code\":\"0000\"}");
                //打印飞鹅订单
                gzhNewsTemplateService.feiePush(payOrderInfo);
                gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);
                //推送清分信息
                gzhNewsTemplateService.pushSettleInfo(payOrderInfo, obj);

            }
        } catch (Exception e) {
            logger.info("云华开始回调错误日志+" + e.getMessage());
            e.printStackTrace();
        }

    }


    // 金控接受异步异步通知
    @RequestMapping(value = "/test11", consumes = "application/json", method = RequestMethod.POST)
    public void test11() {
        // 接受异步消息

        String notifyUrl = "https://" + domainName + contextPath + "/yunHuaNotice";
        HashMap mm = yunHuaPayUtils.yunHuaPayWxMini(YunHuaParam.builder()
                .partnerCode("301055410000405")
                .posOrderNo("112233443123111123100333333111123")
                .noticeUrl(notifyUrl)
                .userId("123123")
                .txnAmt((BigDecimal.valueOf(Double.valueOf(0.01))))
                .openId("oYxhF6MBg3GxA2efNtrOv2PlgM-A")
                .miniUrl("www.baidu.com")
                .build(), "72SANSE4CD9H587A8", yunHuaPrePayUrl);
        String mmmmm = "";
        return;

    }
//     @GetMapping(value = "/feie")
//     public void feieTest(){
// //        gzhNewsTemplateService.feiePush();
//     }

//    @GetMapping(value = "/customerDialogueRegister1")
//    public void customerDialogue(String request){
//        logger.info(request);
//    }


//    public class MyThread  implements Runnable {
//        public void run(){
//
//        }
//    }

    /**
     * 天阙支付-刷卡支付创建订单
     *
     * @param request
     * @param response
     */
    @ApiOperation(value = "天阙支付-刷卡支付创建订单")
    @PostMapping("/tradeReverseBankCardAddOrder")
    @ResponseBody
    public String tradeReverseBankCardAddOrder(@Valid @RequestBody AddPayOrderParam payParameter) {
        log.info("天阙支付-刷卡支付创建订单 参数-{}",JSON.toJSONString(payParameter));
        if (payParameter.getEnableDiscount() == null) {
            payParameter.setEnableDiscount(Boolean.TRUE);
        }
        return payOrderService.bankCardAddOrder(payParameter, PayWayServiceChargeEnum.APPTYPE_BANK_CARD.getValue());
    }

    /**
     * 天阙支付-刷卡支付前端更新订单
     *
     * @param request
     * @param response
     */
    @ApiOperation(value = "天阙支付-刷卡支付前端更新订单")
    @PostMapping("/bankCardUpdateOrder")
    @ResponseBody
    public String bankCardUpdateOrder(@Valid @RequestBody BankCardUpdateOrderParam param) {
        return payOrderService.bankCardUpdateOrder(param);
//        return ResultData.successJson("成功");
    }

    /**
     * 开小票
     *
     * @param invoice 小票信息
     * @return
     */
    @ApiOperation(value = "去开票", httpMethod = "POST", notes = "开发票")
    @PostMapping("/goToInvoice")
    @ResponseBody
    @Transactional
    public String goToInvoice(@Valid @RequestBody GoToInvoice invoice) {

        try {
            //获取输入的开票金额
            Double invoiceAmount = invoice.getInvoiceAmount();
            BigDecimal invoicebigDecimal = new BigDecimal(String.valueOf(invoiceAmount));
            InvoiceInfoVo invoiceInfo =null;
            PayOrder payOrder = null;
            //订单支付金额
            Double amt = 0d;
            if(StringUtils.isEmpty(invoice.getOrderNo())||StringUtils.isEmpty(invoice.getBusinessName())){
                throw new Exception("orderNo、businessName不能为空");
            }
            invoiceInfo = invoiceService.selectInvoiceInfoByOrdNoAndBusinessName(invoice.getOrderNo(),invoice.getBusinessName());

            if(invoice.getBusinessName().equals(GoToInvoice.BUSINESSNAME_PAY_ORDER)){
                payOrder = payOrderService.selectOrderInfoByOrdNo(invoice.getOrderNo());
                if (ObjectUtils.isEmpty(payOrder)) {
                    throw new Exception("没有获取到该订单信息");
                }
                amt = payOrder.getAmt();

            }else if(invoice.getBusinessName().equals(GoToInvoice.BUSINESSNAME_CUSTOMER_CARD_USE_REORD)){
                CustomerCardUseRecord useRecord = customerCardUseRecordMapper.getByOrderNo(invoice.getOrderNo());
                if(useRecord!=null){
                    amt = useRecord.getAmt().doubleValue();
                }else{
                    throw new Exception("没有获取到该订单信息");
                }

            }else if(invoice.getBusinessName().equals(GoToInvoice.BUSINESSNAME_FLEET_CARD_RECHARGE_RECORD)){
                FleetCardRechargeRecord fleetCardRechargeRecord=fleetCardMapper.selectRechargeRecordByRecordId(Long.parseLong(invoice.getOrderNo()));
                if(fleetCardRechargeRecord!=null){
                    amt = fleetCardRechargeRecord.getRechargeAmount().doubleValue();
                }
            }else if(invoice.getBusinessName().equals(GoToInvoice.BUSINESSNAME_PHYSICAL_CARD_BALANCE)){
                PhysicalCardBalance physicalCardBalance = physicalCardBalanceMapper.selectByOrderNo(invoice.getOrderNo());
                if(physicalCardBalance!=null){
                    amt = physicalCardBalance.getAmount().doubleValue();
                }else{
                    throw new Exception("没有获取到该订单信息");
                }
            }else if(invoice.getBusinessName().equals(GoToInvoice.BUSINESSNAME_SUPER_PAY_ORDER)){
                SuperPayOrder superPayOrder=new SuperPayOrder();
                superPayOrder.setSuperOrderNo(invoice.getOrderNo());
                List<SuperPayOrder> superPayOrders = superPayOrderMapper.selectSuperPayOrderList(superPayOrder);
                if(superPayOrders.size()>0){
                    superPayOrder= superPayOrders.get(0);
                }else{
                    throw new Exception("没找到该订单信息");
                }
                amt = superPayOrder.getAmt().doubleValue();
            }
            else{
                throw new Exception("不支持的业务名称");
            }


            BigDecimal amtbigDecimal = new BigDecimal(String.valueOf(amt));
            if (invoicebigDecimal.compareTo(amtbigDecimal) > 0) {
                throw new Exception("开票金额不能超过实付金额");
            }

            if (ObjectUtils.isNotEmpty(invoiceInfo) && invoiceInfo.getInvoiceStatus() == 1) {
                throw new Exception("该订单已全额开票");
            }
            //判断是否部分开票
            if (ObjectUtils.isNotEmpty(invoiceInfo) && invoiceInfo.getInvoiceStatus() == 2) {
                BigDecimal invoiceBalance = new BigDecimal(String.valueOf(invoiceInfo.getInvoiceBalance()));
                if (invoicebigDecimal.compareTo(invoiceBalance) > 0) {
                    throw new Exception("开票金额不能超过剩余可开票金额 --剩余可开金额：" + invoiceInfo.getInvoiceBalance());
                }
                if (invoiceService.updateInvoiceInfo(invoiceInfo, invoice) == 1) {
                    //更新订单开票状态
                    InvoiceInfoVo invoiceInfoStatus = invoiceService.selectInvoiceInfoByOrdNoAndBusinessName(invoice.getOrderNo(),invoiceInfo.getBusinessName());
                    payOrderService.updatePayOrderInvoiceStatusByOrdNoAndBusinessName(invoiceInfoStatus.getOrderNo(), invoiceInfoStatus.getInvoiceStatus(),invoiceInfo.getBusinessName());
                    GoToInvoice build = GoToInvoice.builder()
                            .invoiceAmount(invoice.getInvoiceAmount())
                            .orderNo(invoice.getOrderNo())
                            .build();
                    return ResultData.successJson(build);
                }
            }



                //插入开票信息
                int insertedInvoiceInfo = invoiceService.insertInvoiceInfo(invoice,amt);
                InvoiceInfoVo invoiceInfo1 = invoiceService.selectInvoiceInfoByOrdNoAndBusinessName(invoice.getOrderNo(),invoice.getBusinessName());
                //更新订单开票状态
                int orderInvoiceStatus = payOrderService.updatePayOrderInvoiceStatusByOrdNoAndBusinessName(invoiceInfo1.getOrderNo(), invoiceInfo1.getInvoiceStatus(),invoice.getBusinessName());
                if (insertedInvoiceInfo == 1 && orderInvoiceStatus == 1) {
                    GoToInvoice build = GoToInvoice.builder()
                            .invoiceAmount(invoice.getInvoiceAmount())
                            .orderNo(invoice.getOrderNo())
                            .build();
                    return ResultData.successJson(build);
                }

        } catch (Exception e) {
            logger.info("开发票出错+" + e.getMessage());
            return ResultData.errorJson(e.getMessage());
        }
        return ResultData.errorJson("有问题,请排查");
    }

    @ApiOperation(value = "获取订单开票状态")
    @GetMapping("/getInvoiceStatus")
    @ResponseBody
    public String getInvoiceStatus(@RequestParam String OrderNo) {
        InvoiceInfoVo invoiceInfo = invoiceService.selectInvoiceInfoByOrdNoAndBusinessName(OrderNo,"pay_order");
        Gson gson = new GsonBuilder().serializeNulls().create();
        try {
            if (ObjectUtils.isEmpty(invoiceInfo)) {
                throw new Exception("未找到该订单开票信息");
            }
        } catch (Exception e) {
            logger.error("/getInvoiceStatus-", e);
            return ResultData.errorJson(e.getMessage());
        }
        return gson.toJson(invoiceInfo);

    }

    @ApiOperation(value = "获取订单开票记录")
    @GetMapping("/getInvoiceRecords")
    @ResponseBody
    public List<InvoiceInfoVo> getInvoiceRecords(@RequestParam String OrderNo) {
        return invoiceService.getInvoiceRecords(OrderNo);
    }

    @ApiOperation(value = "多油品拉起支付")
    @PostMapping("multiplePay/toThirdPay")
    @SimpleRepeatedReqLimit(name = "multiplePay:status:",express = "[0].getOpenId()+[0].getAliUserId()",expire = 15)
    public ResultData<Map<String, Object>> toMultipleThirdPay(@RequestBody @Validated MultiplePayInfoReq multiplePayInfoReq){
        return ResultData.success(qujiaPayV2Service.toMultipleThirdPay(multiplePayInfoReq));
    }

    @ApiOperation(value = "多油品支付回调-随行付")
    @PostMapping("multiplePay/callback/sxf")
    public String multiplePayCallbackSxf(@RequestBody Map<String,Object> request){
        return qujiaPayV2Service.callbackSxf(request);
    }

    @ApiOperation(value = "多油品支付回调-云化")
    @PostMapping("multiplePay/callback/yh")
    public String multiplePayCallbackYh(@RequestBody Map<String,Object> request){
        return qujiaPayV2Service.callbackYh(request);
    }


}